AngularJS调用REST API时出现Cannot set property 'data' of undefined错误求助
解决AngularJS中Http GET回调里
this.data赋值报错的问题 嘿,这个问题我碰到过好多次啦!你遇到的TypeError: Cannot set property 'data' of undefined,核心原因是回调函数里的this指向不对——你用普通function定义的回调里,this并不是组件实例的上下文,而是回调函数自身的执行上下文,所以this.data就变成了“给undefined的属性赋值”,自然报错。而console.log能正常打印数据,是因为response是回调的参数,和this没关系~
下面给你三种靠谱的解决方案,任选一种都能解决问题:
方案1:用箭头函数(最简洁,推荐)
箭头函数不会创建自己的this,它会继承外层作用域的this,也就是你的组件实例。直接把回调改成箭头函数就行:
getData(){ this.http({method: 'GET', url: URL}) .then((response) => { console.log(response.data.id); this.data = response.data; // 现在this指向组件实例,赋值成功 }); }
方案2:提前保存this的引用(ES5兼容写法)
如果你的环境还不支持ES6箭头函数,可以在回调外面先把组件的this存到一个变量里(比如self),然后在回调里用这个变量访问组件属性:
getData(){ var self = this; // 保存组件实例的this this.http({method: 'GET', url: URL}) .then(function(response) { console.log(response.data.id); self.data = response.data; // 用self代替this,指向正确的上下文 }); }
方案3:用.bind(this)绑定上下文
给回调函数绑定组件的this,强制让回调里的this指向组件实例:
getData(){ this.http({method: 'GET', url: URL}) .then(function(response) { console.log(response.data.id); this.data = response.data; }.bind(this)); // 绑定this到组件实例 }
这三种方法都能解决你的问题,个人推荐第一种箭头函数的写法,代码更简洁直观~
内容的提问来源于stack exchange,提问作者saran sanjeevi
相关产品推荐
相关产品推荐

