微信小程序中this指向作用域问题this.setData is not a function报错

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

doCalc:function(){
    wx.request({
      url: url,
      method:'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.code == 0){
          this.setData({
            maxCount: res.data.maxCount
          });
        }
      }
    })
  }  

这时会报错this.setData is not a function

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

那么需要怎么修改呢?

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

var _this = this;

然后使用_this 来setData就行了

posted @ 2019-04-18 15:04  坚持一点点  阅读(1023)  评论(0编辑  收藏  举报