Vue组件方法中catch块访问Vuex Store报错:$store未定义
解决Vue中axios回调无法访问$store的问题
你遇到的Uncaught (in promise) TypeError: Cannot read property '$store' of undefined错误,本质是回调函数里的this指向不对。
在你的代码里,catch使用了普通的function(error) { ... }作为回调,这个函数内部的this已经不再指向Vue组件实例了,自然找不到$store属性。这里有两种简单的解决方法:
方法1:使用箭头函数(推荐)
箭头函数不会绑定自己的this,它会继承外层作用域的this,也就是Vue组件实例。修改后的代码如下:
axios.post("/api/model", this.model) .then(response => { window.location.href = "/Home/Index"; }) .catch(error => { // 替换成箭头函数 if (error.response) { this.$store.commit("setServerErrors", error.response.data); } });
方法2:提前保存组件实例的引用
在发起axios请求前,把组件的this存到一个变量里,比如vm(也可以叫其他名字),然后在回调中使用这个变量来访问$store:
const vm = this; // 提前保存组件实例 axios.post("/api/model", this.model) .then(response => { window.location.href = "/Home/Index"; }) .catch(function(error) { if (error.response) { vm.$store.commit("setServerErrors", error.response.data); // 用vm代替this } });
小提示
在Vue组件的异步操作(比如axios请求、定时器)中,优先使用箭头函数处理回调,能有效避免this指向混乱的问题,减少这类常见bug。
内容的提问来源于stack exchange,提问作者raklos
相关产品推荐
相关产品推荐

