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

xiaoxiao2021-03-01  14

在微信小程序中我们一般通过以下方式来修改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 _this = this;

然后使用_this 来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){ _this.setData({ maxCount: res.data.maxCount }); } } }) }

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

例如 :

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

当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

作者:fozero转载自:http://www.cnblogs.com/fozero/p/7841488.html

转载请注明原文地址: https://www.6miu.com/read-3850242.html

最新回复(0)