微信小程序开发踩坑:TypeError: Cannot read property 'setData' of undefinedk OR this.setData is not a function

微信小程序开发过程中,需要使用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作用域的问题有两种解决办法

  1. 将回调函数,写成监听函数,监听Pages事件。
     success:res=>{ ,,,,,,,}
  1. 增加一个变量来保存this的作用域
var that = this
success: function(res){
,,,,
.then(res=>{that.setData({imageFiles:res.fileID})
,,,,
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值