微信小程序错误this.setData报错及解决过程
先说原因:
function声明的函数和箭头函数的作用域不同,这是一个不小心坑的地方。可参考箭头函数说明:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
所以对于这个结果,还是换回es5的function函数去写最好了。
箭头函数和function的区别:
- 箭头函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象
- 箭头函数不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误
- 箭头函数不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用Rest参数代替,不可以使用yield命令,因此箭头函数不能用作Generator函数。
这么写会报错
thirdScriptError this.setDataisnotafunction;atpages/index/indexonLoadfunction;atapigetSystemInfosuccesscallbackfunction TypeError:this.setDataisnotafunction
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始终指向函数定义时的thislang:res.language
})console.log(res.language)
}
})
或者这样:
onLoad:function(){
varthat=this;
wx.getSystemInfo({
success:function(res){
that.setData({
lang:res.language
})
console.log(res.language)
}
})
可以用如下示例说明:
'usestrict';
varobj={
i:10,
b:()=>console.log(this.i,this),
c:function(){
console.log(this.i,this);
}
}
obj.b();//printsundefined,Window{...}(ortheglobalobject)
obj.c();//prints10,Object{...}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。