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
      });
    },
  });
}
即可。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM