I’m trying to assign response.data.Response.displayName
from my GET request to my playerName property, however, I am getting an error “Uncaught (in promise) TypeError: Cannot set property 'playerName' of undefined at eval
“. I am successfully console logging response.data.Reponse.displayName
so there is a displayName in it.
Why am I getting this error?
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) }); } }
Advertisement
Answer
Other comments and answers are correct – using an arrow/lambda function instead of just function
will work. But there’s a nuance as to why.
Javascript’s concept of this
is well defined but not always what you’d expect from other languages. this
can change within one scope block when you’re executing from sub-functions of things like callbacks. In your case, the function in the then
no longer understands this
as the same as if you were running the same code directly inside mounted()
.
You can bind functions, however, to (among other purposes) have a specific this
attached that can’t be changed. Arrow functions do this implicitly, and bind this
to what this
is in the context the arrow function is created. Therefore, this code:
axios.get('/User/GetBungieNetUserById/19964531/') .then((response) => { this.playerName = response.data.Response.displayName console.log(response.data.Response.displayName) });
understands this
properly. It is (roughly!) equivalent to the following:
axios.get('/User/GetBungieNetUserById/19964531/') .then((function(response) { this.playerName = response.data.Response.displayName console.log(response.data.Response.displayName) }).bind(this));