微信小程序 this.setData is not a function

  在通常的函數中:javascript

1 bindFaChange1: function (e) {
2     console.log('picker發送選擇改變,攜帶值爲', e.detail.value)
3     this.setData({
4       index1: e.detail.value
5     })
6   }

  this.setData是正確的。java

  但當在函數中有個請求(wx.request)時:json

 1 formSubmit: function (e) {
 2     wx.request({
 3       method: 'POST',
 4       header: header,
 5       url: url,
 6       dataType: 'json',
 7      success: function (res) {
 8            this.setData({
 9               data1: true
10             })
11       }
12     })
13 }

  或者執行定時任務時候:函數

 1 var si = setInterval(function () {
 2         that.setData({
 3           sendVerifyingCodeText: curCount + '秒後從新獲取'
 4         });
 5         that.setData({
 6           sendSmsCodeDisable: true
 7         });
 8         curCount--;
 9         if (curCount <= 0) {
10           that.setData({
11             sendSmsCodeDisable: false
12           }),
13           clearInterval(si);
14         }
15       }, 1000);

  這樣會報錯誤:this.setData is not a function.this

  這個在新的函數內的this表明的是這個函數體,全部是沒有this.setData。這個相似java中的this指的是當前對象,可是javascript是以函數爲主體的,因此就是this在函數內部就當前函數。修改未:url

  解決方法就是 :在請求(wx.request)或者新的非當前js的方法外面添加:var that=this;而後用:spa

1 that.setData({
2               data1: true
3             })
相關文章
相關標籤/搜索