在微信小程序开发过程中,肯定会遇到过这个错误吧
VM447 WAService.js:2 TypeError: Cannot read property ‘data’ of undefined

这里遇到的就是this指代问题,可以看下面的例子
/**
* 页面的初始数据
*/
data: {
list:null
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.request({
url: 'https://***/***/shop/goods/list',
success:function(res){
this.data.list = res.data
}
})
},
通过wx.request请求列表,得到的结果赋值给data中的list
这时就回报错VM447 WAService.js:2 TypeError: Cannot read property ‘data’ of undefined
因为this的作用域发生了变化,在网络请求的回调函数中是访问不到data中的变量的。
解决方法1:使用this指代,将this保存到变量that中,在需要用this的地方使用that.data.list
onLoad: function (options) {
let that = this
wx.request({
url: 'https://***/***/shop/goods/list',
success:function(res){
that.data.list = res.data
}
})
},
解决方法2:使用es6的箭头函数
onLoad: function (options) {
wx.request({
url: 'https://***/***/shop/goods/list',
success:(res)=>{
this.data.list = res.data
}
})
},
在微信小程序的onLoad函数中,通过wx.request获取数据并尝试赋值给data.list时出现TypeError,原因是回调函数内的this不再指向当前对象。解决方法包括:1) 使用变量that保存this的引用,然后用that.data.list赋值;2) 使用ES6的箭头函数,保持this指向。这两种方式都能有效解决this的作用域问题。
695

被折叠的 条评论
为什么被折叠?



