Vue中axios回调调用this.$router提示undefined该如何解决?
问题原因
报错的核心是catch回调函数的this指向错误,不是Vue组件实例,所以无法读取到挂载在实例上的$router属性。
你在登录、注册组件中调用this.$router.push时,this处于组件实例的正常上下文,所以可以正常执行;但在loadCollections方法的catch回调中,你使用了普通函数写法function (error){},普通函数的this是运行时绑定的,axios异步回调的执行上下文不属于Vue组件,此时this值为undefined,就会触发你看到的报错。而你上方的then回调使用了箭头函数,箭头函数的this继承自外层作用域(也就是loadCollections方法的this,即组件实例),所以then里的this可以正常使用。
解决方案
有三种常用的修复方式,优先推荐第一种:
方案1:将catch回调改为箭头函数
和then的写法保持一致,直接继承外层的this指向:
loadCollections(){ axios.get('/api/documentCollections') .then((response) => { this.Collections = response.data.data this.disableButtons(response.data.data); }) // 改为箭头函数 .catch((error) => { if(error.response.status === 422){ this.$router.push({ name: "Settings"}); } }); },
方案2:提前保存组件实例指向
如果需要兼容旧的JS语法,可以在外层预先存储this的指向,在回调中使用存储的变量调用$router:
loadCollections(){ // 预先保存组件实例 const vm = this; axios.get('/api/documentCollections') .then((response) => { this.Collections = response.data.data this.disableButtons(response.data.data); }) .catch(function (error){ if(error.response.status === 422){ vm.$router.push({ name: "Settings"}); } }); },
方案3:为回调手动绑定this
使用bind方法手动将回调的this绑定为组件实例:
loadCollections(){ axios.get('/api/documentCollections') .then((response) => { this.Collections = response.data.data this.disableButtons(response.data.data); }) .catch(function (error){ if(error.response.status === 422){ this.$router.push({ name: "Settings"}); } }.bind(this)); // 手动绑定this },
你的路由配置没有问题,Settings和DocumentCollections同为Dashboard的子路由,使用name跳转的逻辑是正确的,修复this指向后就可以正常跳转。
内容的提问来源于stack exchange,提问作者iSnuff
相关产品推荐
相关产品推荐

