如何在catch error axios中设置/更改变量



如果我在axios错误时尝试在vue2中设置变量,我会得到以下信息:Uncaught(in promise(TypeError:无法设置未定义的属性(设置"snackbar"(

axios.post('/testaxios', {
}).then(response => {
console.log(response.data);
}).catch(function (error) {
console.error(error);
this.snackbar = true;
});
data() {
return {
snackbar: false,
}
}

您需要将catch函数绑定到this上下文:

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

或者简单地使用箭头功能(自动绑定(:

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

最新更新