微信小程序错误this.setData报错及解决过程

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

微信小程序错误this.setData报错及解决过程

岌岌可危   2020-05-17 我要评论

先说原因:

function声明的函数和箭头函数的作用域不同,这是一个不小心坑的地方。可参考箭头函数说明:

https:/https://img.qb5200.com/download-x/developer.mozilla.org/en-UShttps://img.qb5200.com/download-x/docs/Web/JavaScript/Reference/Functions/Arrow_functions

所以对于这个结果,还是换回es5的function函数去写最好了。

箭头函数和function的区别:

  • 箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象
  • 箭头函数不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误
  • 箭头函数不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替,不可以使用yield命令,因此箭头函数不能用作Generator函数。

这么写会报错

thirdScriptError
this.setData is not a function;at pages/index/index onLoad function;at api getSystemInfo success callback function
TypeError: this.setData is not a function
onLoad: function () {
  wx.getSystemInfo({
   success: function (res) {
    this.setData({
     lang: res.language
    })
    console.log(res.language)
   }
  })

这么改一下就不报错了。

onLoad: function() {
  wx.getSystemInfo({
    success: (res) = >{
      this.setData({箭头函数的this始终指向函数定义时的this lang: res.language
      }) console.log(res.language)
    }
  })

或者这样:

onLoad: function () {
  var that=this;
  wx.getSystemInfo({
   success: function (res) {
    that.setData({
     lang: res.language
    })
    console.log(res.language)
   }
  })

可以用如下示例说明:

'use strict';
var obj = {
 i: 10,
 b: () => console.log(this.i, this),
 c: function() {
  console.log(this.i, this);
 }
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们