-1

If i try set variable in vue2 when axios error i get this: Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'snackbar')

            axios.post('/testaxios', {
            }).then(response => {
                console.log(response.data);
            }).catch(function (error) {
                console.error(error);
                this.snackbar = true;
            });
data() {
        return {
            snackbar: false,
        }
}
aurorame
  • 31
  • 6
  • 1
    Does this answer your question? [Using Axios in VueJS - this undefined](https://stackoverflow.com/questions/53657696/using-axios-in-vuejs-this-undefined) – ATOMP Mar 25 '22 at 23:09

1 Answers1

1

You either need to bind the catch function to the this context:

catch(function(error) {
  console.error(error);
  this.snackbar = true;
}).bind(this);

Or simply use an arrow function (which does the binding automatically):

catch((error) => {
  console.error(error);
  this.snackbar = true;
});
Ben
  • 1,331
  • 2
  • 8
  • 15