微信小程序中 this.setData is not a function报错

在微信小程序中我们一般通过以下方式来修改data中的数据:

比如获取小程序缓存:

wx.getStorage({
      key: 'is_screen',
      success: function (res) {
        this.setData({
          is_screen: res.data
        })
      }
    })

但是会报错:

this.setData is not a function

这是因为this作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过this来setData

那么需要怎么修改呢?

我们通过将当前对象赋给一个新的对象

var that = this;

然后使用_this 来setData就行了

完整代码:

/**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'is_screen',
      success: function (res) {
        this.setData({
          is_screen: res.data
        })
      }
    })
  },

可以关注微信公众号 lovephp,

原文地址:https://www.cnblogs.com/ldj3/p/9139695.html