Talking about the callback function of vue using axios this does not point to vue instance but is undefined

  • 2021-08-28 07:10:15
  • OfStack

Today, when using axios in the project of vue-cli scaffolding, I encountered an error message that could not be resolved for this. $route, and finally found that it was a problem of scope.

1. Solution: Use = >

Original code:


axios.get('/user', {
  params: {
   ID: 12345
  }
 })
 .then(function (response) {
  console.log(response);
 })
 .catch(function (error) {
  console.log(error);
 });

Amend to read:


axios.get('/user', {
  params: {
   ID: 12345
  }
 })
 .then((response) => {
  console.log(response);
 })
 .catch((error) => {
  console.log(error);
 });

2.= > Analyse

In JS, the arrow function is not a simple syntax sugar for function () {} anonymous function. In fact, there is an obvious difference between arrow function and anonymous function: this inside arrow function is lexical scope, which is determined when writing function and determined by context. The this of an anonymous function points to the object that actually calls the method at runtime and cannot be determined when the function is written.

Can't be used as a constructor, that is, you can't use the new command, otherwise an error will be thrown.

this, arguments, caller and other objects do not exist in the function body.

The yield command cannot be used, so the arrow function cannot be used as an Generator function.

The arrow function has no other objects except the passed parameters! If the arrow function refers to variables other than this, arguments, or parameters, they are not contained by the arrow function itself, but inherited from the parent scope.

Additional knowledge: this pointer problem in callback function requested in axios

Look at the following two sets of codes


this.axios.post(url, data)
.then(function(result) {
var resData = result.data
console.log(resData)
if (resData.status === 1) {
} else {
}
})
.catch(function (error) {
console.log(error)
})


this.axios.post(url, data)
.then((result) => {
var resData = result.data
console.log(resData)
if (resData.status === 1) {
} else {
}
})
.catch(function (error) {
console.log(error)
})

The difference between these two sets of code is that the callback function after the request is successful, one uses anonymous function and one uses arrow function

Pointers to anonymous functions point to- > Function operation itself

The pointer to the arrow function points to- > Component

That is to say, when you need to use variables or functions declared in components, you need to use arrow functions


Related articles: