微信小程序开发过程中,需要使用this.setData来设置变量,偶尔会出现TypeError: Cannot read property ‘setData’ of undefinedk OR this.setData is not a function的报错。
其实这样的异常经常在调用各种API的回调函数(success:function(res) fail:function(res) complete:function(res))当中,使用this相关方法和属性中出现的。
拿一段带bug的上传图片至数据库的云开发代码来讲解。
upImages:function(){
wx.chooseImage({
success: function(res){
wx.cloud.uploadFile(
cloudPath: `${ Math.floor(Math.random() * 10000) }.png`,
filePath: res.tempFilePaths[0]})
.then(res=>{this.setData({imageFiles:res.fileID})})
.catch(err=>{console.log(err)});
wx.showToast({ title: '上传成功', }) }, }) },
调用了wx.chooseImage选择图片的api,在success回调函数中直接this.setData就会报错了,原因是此时this变量的指向作用域不再是Pages对象了(js中的Pages数组)仅限于success函数中针对this作用域的问题有两种解决办法
- 将回调函数,写成监听函数,监听Pages事件。
success:res=>{ ,,,,,,,}
- 增加一个变量来保存this的作用域
var that = this
success: function(res){
,,,,
.then(res=>{that.setData({imageFiles:res.fileID})
,,,,
}