在一般的函數中:
1 bindFaChange1: function (e) { 2 console.log('picker發送選擇改變,攜帶值為', e.detail.value) 3 this.setData({ 4 index1: e.detail.value 5 }) 6 }
this.setData是正確的。
但當在函數中有個請求(wx.request)時:
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.setData。這個類似java中的this指的是當前對象,但是javascript是以函數為主體的,所以就是this在函數內部就當前函數。修改未:
解決方法就是 :在請求(wx.request)或者新的非當前js的方法外面添加:var that=this;然后用:
1 that.setData({ 2 data1: true 3 })