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