微信小程序中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
最后
以上就是痴情豆芽最近收集整理的关于微信小程序中this.setData is not a function报错问题的全部内容,更多相关微信小程序中this.setData内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复