I am coming from this question where I couldn't use this
inside the following method:
methods: {
changeUrl: _.debounce((e) => {
this.settings.url = e.target.value;
}, 500),
},
This threw Uncaught TypeError: Cannot read property 'settings' of undefined
.
The answer was that we can't use this
inside arrow functions:
An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to the
this
,arguments
,super
, ornew.target
keywords.
But then I've noticed that I was using arrow functions inside axios handlers:
sendData() {
server
.post("/endpoint", data)
.then(res => {
if (res.status == 200) {
this.message = "Data was sent";
} else {
this.message = "Something went wrong. Please try again";
}
})
.catch(error => {
this.message = "";
console.log(error);
});
},
And the above code isn't throwing any error and is working perfectly.
Why isn't this.message
throwing Uncaught TypeError: Cannot read property 'message' of undefined
What's more, if I change the above code to use normal functions instead of arrow functions:
sendData() {
server
.post("/endpoint", data)
.then(function(res) {
if (res.status == 200) {
this.message = "Data was sent";
} else {
this.message = "Something went wrong. Please try again";
}
})
.catch(function(error) {
this.message = "";
console.log(error);
});
},
this will throw Uncaught TypeError: Cannot read property 'message' of undefined
.
Why ?