0
点赞
收藏
分享

微信扫一扫

TypeError: Cannot read property ‘push‘ of undefined


问题原因​​this​​​没有指向​​data​​​,出现​​this​​​作用域问题(解决方法,在函数外层​​const that = this​​​,利用​​that​​​代替​​this​​)

原代码:

TypeError: Cannot read property ‘push‘ of undefined_leechoy

报错

​[system] TypeError: Cannot read property 'push' of undefined at Function.success (pages-index-index.9f60a9e14becec7424f4.hot-update.js:59) at chunk-vendors.js:186 at Object.I [as callback] (chunk-vendors.js:186) at b (chunk-vendors.js:186) at XMLHttpRequest.k.onload (chunk-vendors.js:186)​

验证:

(打印this 值)

got(){
uni.request({
url:'http://api.tianapi.com/txapi/caipu/index?key=905c6456ae5c3c2bc0568f0b9d78815b&word='+this.name,
method:'GET',
data:{},
success: function(res) {
console.log(this)
console.log(res.data.newslist[0]);
// let cooks = res.data.newslist;
this.cook.push(res.data.newslist[0]);
}
}
)
}

显示结果如下,可知this指向了我们的回调函数success

ƒ success(res) {
__f__("log", this, " at pages/index/index.vue:48");
__f__("log", res.data.newslist[0], " at pages/index/index.vue:49");
// let cooks = res.data.newslist;
… " at pages/index/index.vue:48"

利用外层​​const that = this​​​ ,用​​tha​​​t代替内层的​​this​​可以解决域问题

got(){
const that = this;
uni.request({
url:'http://api.tianapi.com/txapi/caipu/index?key=905c6456ae5c3c2bc0568f0b9d78815b&word='+this.name,
method:'GET',
data:{},
success: function(res) {
console.log(res.data.newslist[0]);
// let cooks = res.data.newslist;
that.cook.push(res.data.newslist[0]);
}
}

)
}
}
}


举报

相关推荐

0 条评论