微信小程序中this.setData is not a function报错问题
- 新手在编写小程序时经常会遇到的一种错误。
新手在编写小程序时经常会遇到的一种错误。
在小程序中,通常我们用setData修改数据,用于函数时不会报错。
eg.
setData function(e){this.setData({mobileLocation: mobileLocation,});
}
这是正确的写法,但在wx.setLocation等这类的wx请求中会报错呢?
wx.getLocation({success: function(res) {this.setData({mobileLocation: mobileLocation,});},})
原因 : 因为this作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过this来setData
那么需要怎么修改呢?
我们通过将当前对象赋给一个新的对象
var that = this;
再使用that来setData就不会报错了!
var that = this;
wx.getLocation({success: function(res) {that.setData({mobileLocation: mobileLocation,});},})
原文出处:
作者:fozero
https://www.cnblogs.com/fozero