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 @ 2020-02-19 04:15  WaterGe  阅读(5615)  评论(1编辑  收藏  举报