TypeError: Cannot read property ‘push‘ of undefined
问题原因
this
没有指向data
,出现this
作用域问题(解决方法,在函数外层const that = this
,利用that
代替this
)
原代码:
报错
[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]);
}
}
)
}
}
}
还没有评论,来说两句吧...