微信小程序 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             })
相关文章
相关标签/搜索