Cannot read property 'setData' of undefined【转载】
发布于 4 年前 作者 gtian 1296 次浏览 来自 分享

场景

自己在调用wx.getSystemInfo({})时,开发工具自动补全了代码。在success回调中按照以往的写法调用this.setData({ });时,报错:TypeError: Cannot read property 'setData' of undefined。

相关代码如下:

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: function (res) {
        console.log(res);
        this.setData({
          system_info: res.brand,
        });
      },
      fail: function (res) {
        this.myShowError("获取手机系统信息")
      },
      complete: function (res) { },
    })

  },

仔细对比和之前绑定事件调用this.setData({ });时相比,调用方式并没有什么差别。因为刚接触小程序开发,success: function (res) {};这种写法没见过,所以猜想问题可能出在这里了。该用以下方式即可正常使用。

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSystemInfo({
      success: (res) => {
        console.log(res);
        this.setData({
          system_info: res.brand,
        });
      },
      fail: function (res) {
        this.myShowError("获取手机系统信息")
      },
      complete: function (res) { },
    })

  },

解决方案

success: function (res) {
   this.setData({})
}

改成了:

success: (res) =>  {
   this.setData({})
}

【原因分析】为什么呢?

因为两种写法this指向不同。

success: (res) => {
        console.log("(res) => { }时:" + this);
      },

--------------

success: function (res){
        console.log("function (res)时:" + this);
       },

对比分析:

function (res)时:undefined
 (res) => { }时:[object Object]

function (res)写法时 ,thisundefined未定义的。

(res) => { }写法时thisObject

【分析总结】

1、如果函数作为对象的方法调用,this指向的是这个上级对象,即调用方法的对象。

2、如果是构造函数中的this,则this指向新创建的对象本身。

作者:TensorFlow开发者 链接:https://www.jianshu.com/p/4f7b33e3e1df 感谢原作者的倾力奉献!

回到顶部