问题
微信小程序开发的项目某个函数中,按照官方文档引入了一个弹框,并在成功的回调中改变data数据:
wx.showModal({
title: '提示',
content: '确认全部删除吗?',
success (res) {
if (res.confirm) {
console.log('用户点击确定');
console.log('this');
//清空data中的historyList
this.setData({
historyList: []
})
//移除本地的历史记录缓存
wx.removeStorageSync('searchHistory');
}
}
})
突然报错TypeError: Cannot read property ‘setData’ of undefined,其他的this.setData都没有问题。
原因
首先我们分析一下造成setData未定义的原因,没错前面我们有讲到这是一个回调函数object.success ,这就涉及了js中的回调函数this的指向问题,这里是在回调函数里打印一下这个this和报错信息:
this打印出的是undefined(原因是this指向success这个回调函数还是this指向的wx.showModal这个方法?),而不是我们想要的pages,所以导致了seyData未定义,我们需要的是回调函数外层的this
解决问题方法一
既然我们需要回调函数外层的this,我们可以先在外层把this赋值给一个变量a,在回调函数里写a.setData,如图:
var that = this;
console.log(this)
//点击删除时的弹框
wx.showModal({
title: '提示',
content: '确认全部删除吗?',
success (res) {
//console.log(res)
if (res.confirm) {
console.log('用户点击确定');
console.log(that);
//清空data中的historyList
that.setData({
historyList: []
})
//移除本地的历史记录缓存
wx.removeStorageSync('searchHistory');
}
}
})
我们把外层的this赋值给了that,再由that带给回调函数,这时打印一下that,会得到我们想要的pages,也不会进行setData的报错:
解决问题方法二
我们可以利用ES6中的箭头函数的特性,它没有自己的this,它的this继承外部函数的作用域,因此刚好是我们想要的外层this,这个方法只需要我们把回调函数改为箭头函数,比较方便。代码如下:
//点击删除时的弹框
wx.showModal({
title: '提示',
content: '确认全部删除吗?',
success:(res) => {
//console.log(res)
if (res.confirm) {
console.log('用户点击确定');
console.log(this);
//清空data中的historyList
this.setData({
historyList: []
})
//移除本地的历史记录缓存
wx.removeStorageSync('searchHistory');
}
}
})
打印出来的this结果就是我们想要的外层this,与方法一结果一致。