TypeError: Cannot read property ‘push‘ of undefined

Bertha 。 2022-09-03 06:29 305阅读 0赞

问题原因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 值)

  1. got(){
  2. uni.request({
  3. url:'http://api.tianapi.com/txapi/caipu/index?key=905c6456ae5c3c2bc0568f0b9d78815b&word='+this.name,
  4. method:'GET',
  5. data:{ },
  6. success: function(res) {
  7. console.log(this)
  8. console.log(res.data.newslist[0]);
  9. // let cooks = res.data.newslist;
  10. this.cook.push(res.data.newslist[0]);
  11. }
  12. }
  13. )
  14. }
显示结果如下,可知this指向了我们的回调函数success
  1. ƒ success(res) {
  2. __f__("log", this, " at pages/index/index.vue:48");
  3. __f__("log", res.data.newslist[0], " at pages/index/index.vue:49");
  4. // let cooks = res.data.newslist;
  5. " at pages/index/index.vue:48"

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

  1. got(){
  2. const that = this;
  3. uni.request({
  4. url:'http://api.tianapi.com/txapi/caipu/index?key=905c6456ae5c3c2bc0568f0b9d78815b&word='+this.name,
  5. method:'GET',
  6. data:{ },
  7. success: function(res) {
  8. console.log(res.data.newslist[0]);
  9. // let cooks = res.data.newslist;
  10. that.cook.push(res.data.newslist[0]);
  11. }
  12. }
  13. )
  14. }
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,305人围观)

还没有评论,来说两句吧...

相关阅读