0

I have a very basic Vue component in which I want to call a method recursively within a setTimeout.

Calling the method (once) from the mounted lifecycle works as expected. But then calling itself always gives a Uncaught TypeError: ... is not a function.

new Vue({
  el: '#app',
  mounted() {
    this.check();
  },
  methods: {
    check: () => {
      console.log('Checking');
      
      // error: self.check is not a function
      let self = this;
      setTimeout(function() {
        self.check();
      }, 500);

      // error: this.check is not a function
      setTimeout(function() {
        this.check();
      }.bind(this), 500);

      // does nothing
      setTimeout(this.check, 500);

      // error: this.check is not a function
      setTimeout(() => {
        this.check();
      }, 500);
    },
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app"></div>
Chris
  • 3,680
  • 6
  • 26
  • 43
  • 4
    Don't use an arrow function when defining Vue instance methods, it binds `this` to the window. – thanksd Oct 17 '17 at 18:28
  • @thanksd Does that always apply to both the lifecycle methods **and** the regular methods (in `methods: {}`)? – Chris Oct 17 '17 at 18:35
  • 1
    Yes. Arrow functions in javascript always bind `this` to the enclosing context. In your case, the enclosing context is the window object. – thanksd Oct 17 '17 at 18:39

0 Answers0