一、背景描述
用VUE的时候报这个错
Uncaught TypeError: Cannot read property ‘dispatch’ of undefined
二、问题分析
1、我的代码是酱紫滴
data() {return {// 计时器whole_timer: null}},
created() {this.isLoginOut();},
isLoginOut() {console.log("11111:" + this)clearInterval(this.whole_timer);this.whole_timer = setInterval(function () {console.log("22222:" + this)// 判断一下是否超时,如果超时了就退出this.$store.dispatch('user/logout');this.$router.push(`/login?redirect=${this.$route.fullPath}`);// 如果退出了就清除这个定时器setTimeout(function() {clearInterval(this.whole_timer);}, 1000);}, 1000);}
2、是为什么捏
这是因为this指针发生了变化,在代码里打了两个日志看下this是啥
这是因为最开始的时候this指针是Vue实例
可以看下VUE官方文档中的生命周期钩子函数
Vue官方文档
但是在setInterval方法跑的时候,后面this指针就指向了window对象了
3、怎么改嘞
就是把刚才的指向Vue实例的this指针备份一下,就好了
isLoginOut() {console.log("11111:" + this)clearInterval(this.whole_timer);// 这里要备份一下this指针let _this = this;this.whole_timer = setInterval(function () {console.log("22222:" + this)console.log("33333:" + _this)// 判断一下是否超时,如果超时了就退出_this.$store.dispatch('user/logout');_this.$router.push(`/login?redirect=${_this.$route.fullPath}`);// 如果退出了就清除这个定时器setTimeout(function() {clearInterval(_this.whole_timer);}, 1000);}, 1000);}
这里有的人喜欢用_this作为变量名,也有喜欢用self的,也有喜欢用that的,随便吧,反正就是备份一下this指针就可以啦
遇到这种类型的问题,虽然代码可能跟我写的不一样,但是解决的思路差不多,可以先把不同位置的this打印出来,看看是不是变了,如果变了就备份一下就好啦~ 开心~