this.setData is not a function解决

在写小程序时,通常在回调函数时使用this.setData({});时编译器会报this.setData is not a function的错误

因为this作用域指向问题 ,success函数实际是一个闭包 , 无法直接通过this来setData

解决方法有2个:

1 改造回调函数的方法为es6写法:

success: function(res){
  this.setData({});
},
改造为
success: (res)=>{
  this.setData({});
},
即可。
因为当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
 
2 在函数开始时定义一个变量指向this
addImg:function(){
  wx.chooseImage({
    success: function(res){
      var tempFilePaths= res.tempFilePaths;
      this.setData({
        picUrl: tempFilePaths[0],
   temPath: tempFilePaths
      });
    },
  });
}
改造为:
addImg:function(){
  var _this = this;
  wx.chooseImage({
    success: function(res){
      var tempFilePaths= res.tempFilePaths;
      _this.setData({
        picUrl: tempFilePaths[0],
   temPath: tempFilePaths
      });
    },
  });
}
即可。
posted @   WaterGe  阅读(6192)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示