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

  • Post author:
  • Post category:小程序


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

this.setData({
      index1: e.detail.value
    })

比如在函数里面修改数据

bindFaChange1: function (e) {
    this.setData({
      index1: e.detail.value
    })
  }

但是当我们通过wx.request请求网络数据成功后绑定数据时候报以下错误

this.setData is not a function

代码如下

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作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过this来setData

那么需要怎么修改呢?

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

var that = this;

然后使用that 来setData就行了

完整代码

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

另外说一下 , 在es6中 , 使用箭头函数是不存在这个问题的

例如

setTimeout( () => {
            console.log(this.type + ' says ' + say)
        }, 1000)

当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。

并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this


箭头函数里面根本没有自己的

this

,而是引用外层的

this




版权声明:本文为CSDN博主「So灬低调」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/u012717715/article/details/90667758