版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/82585008
在微信小程序中js提供了修改布局状态的函数
this.setData({element: property})
但是有时候调用这个 Console 会报错
类似这样,在回调函数中调用了它就报错,普通函数这样是没有问题的。【具体不明白微信的底层原因】
回调函数有如: setTimeout(arg1, arg2, [arg3]), setInterval(....) 之类的
解决方法
check_in: function() {
// 坑,使用this再回调函数里会一直报错
var other = this
// 使用this不报错
this.setData({done_tip:"今天已经签到了"})
// 使用this报错,用其他赋了this值的变量不报错
setTimeout(function(){other.setData({ success_tip: ""})}, 1500)
}
方法就是在回调函数中使用新定义的变量(此变量先被赋值this)
续:如果在回调函数中调用回调函数(两层回调),需要定义两个新变量
onLoad: function () {
// 普通调用
this.setData({a:1})
var other1 = this
setInterval(function() {
// 一层回调
other1.setData({ check_status: (flag == true ? 1 : 0)})
// 需要继续定义新的赋了other1值的变量,other1不能使用了,而且不能other2 = this,也会报错
// 另外写回调函数使用新定义that也是报错,传参数也报错
setTimeout(function(){var other2 = other1; other2.setData({new_day:""})}, 1000)
}, 10000)
}