【发布时间】:2019-05-31 05:09:43
【问题描述】:
我正在尝试将 GET 请求中的 response.data.Response.displayName 分配给我的 playerName 属性,但是,我收到错误“Uncaught (in promise) TypeError: Cannot set property 'playerName' of undefined at eval”。我成功地在控制台记录了response.data.Reponse.displayName,所以里面有一个displayName。
为什么会出现这个错误?
export default {
data: function() {
return {
playerName: ''
}
},
methods: {
},
mounted() {
axios.get('/User/GetBungieNetUserById/19964531/')
.then(function(response) {
this.playerName = response.data.Response.displayName
console.log(response.data.Response.displayName)
});
}
}
【问题讨论】:
-
使用
(response) => { this.playerName = ...}。使用function关键字,您将失去原来的this上下文 -
使用箭头函数代替:
response=>{ this.playerName = /*..rest of code */} -
嗯,这种情况下一定要使用箭头函数吗?
-
你可以在 axios 调用之前使用
let that=this,并在回调中使用that而不是this -
@Bobimaru 不,你可以做到
function(response){/* code */}.bind(this)
标签: javascript vue.js vuejs2 axios