SoFunction
Updated on 2025-04-05

A brief discussion on the callback function of vue using axios, this does not point to vue instance, but is undefined

When using axios in a project built by vue-cli scaffolding, I encountered the error message of this.$route that cannot be parsed, and finally found that it was a scope problem.

1. Solution: Use =>

Original code:

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

Modified to:

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

2.=>Analysis

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

It cannot be treated as a constructor, that is, the new command cannot be used, otherwise an error will be thrown.

Objects such as this, arguments, callers, etc. do not exist in the function body.

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

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

Supplementary knowledge:This pointer problem in the requested callback function in axios

Please see the following two sets of codes

(url, data)
.then(function(result) {
var resData = 
(resData)
if ( === 1) {
} else {
}
})
.catch(function (error) {
(error)
})

(url, data)
.then((result) => {
var resData = 
(resData)
if ( === 1) {
} else {
}
})
.catch(function (error) {
(error)
})

The difference between these two sets of codes is: the callback function after the request is successful, one uses anonymous function and the other uses an arrow function

Anonymous function pointer to -> function operation itself

The pointer of the arrow function points to -> Component

That is to say, when you need to use variables or functions declared in the component, you need to use arrow functions.

In the above article, this article does not point to vue instances in the callback function of vue using axios. It is undefined. It is all the content I share with you. I hope it can give you a reference and I hope you support me more.