Why I've gotten "Uncaught TypeError: Cannot read property 'counter' of undefined" despite I'm using arrow function for SetTimeout?

Why I've gotten "Uncaught TypeError: Cannot read property 'counter' of undefined" despite I'm using arrow function for SetTimeout?

以下小倒计时应用程序导致 Uncaught TypeError: Cannot read 属性 'counter' of undefined at the timing of evaluation of this.counter .

<template>
  <v-app>
    <v-content>
      Redirect after {{counter}} sec.
    </v-content>
  </v-app>
</template>

<script>
/* eslint-disable no-console */
export default {
  name: 'App',

  components: {
  },
  mounted() {
    this.countdown();
  },
  created() {
  },
  methods: {
    countdown: () => {
      setTimeout(() => {
        if (--this.counter <=0){
          location.href=this.$redirectURL;
        } else {
          this.countdown();
        }
      }, 1*1000);
    }
  },

  data: () => ({
    counter: 5,
  }),
};
</script>

Uncaught TypeError: Cannot read 属性 'counter' of undefined 如下:

我不知道为什么 coutner 被评估为 undefined 尽管我使用的是箭头函数,这意味着“this pointer" 必须是词法的。感谢您的建议!

countdown函数是一个箭头函数,也就是说它里面的this是从外部作用域继承的。 setTimeout 回调也是如此。所以,这里:

export default {
  // ...
  methods: {
    countdown: () => {
      setTimeout(() => {
        if (--this.counter <=0){
          location.href=this.$redirectURL;
        } else {
          this.countdown();
        }
      }, 1*1000);
    }
  },
  // ...
}

this指的是模块顶层的this,在你的设置中是undefined

您希望 this 改为引用当前实例:调用 countdown 时,它应该 捕获 新的 this 值(实例的),而不是继承外部作用域的 this。所以,改变:

countdown: () => {

countdown() {

或到

countdown: function() {