0

When I try to call a function from within a timeout function I get Uncaught TypeError: this.checkMounted is not a function The function runs fine when it's not within the timeout.

How do I correctly access this.function

methods: {
  checkMounted: function () {    
},
mounted() {
  setTimeout(function(){ 
     this.checkMounted()
  }, 3000); 
}

Thank you

Uriah Gray
  • 15
  • 4

1 Answers1

2

1) This is the problem of this binding. You can use the arrow function to solve this problem. CODESANDBOX

Pass arrow function instead of normal function in setTimeout

setTimeout(() => {
      this.logValues();
    }, 2000);

instead of

setTimeout(function(){
      this.logValues();
    }, 2000);

When you use a normal function then this binding is dependent on how the function is called. Here this will be Window object and there is no method named checkMounted on the window object and produces an error.

You can read more about this on stackoverflow


2) There is one more way that you could solve this problem, This is an old-school method and was used before ES6 arrow function. CODESANDBOX

  mounted() {
    const that = this;
    setTimeout(function () {
      that.logValues();
    }, 2000);
  },
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • Thank you, I'll read more about `this`. It looks pretty dense, but to recap, I'm not accessing the global function called checkMounted. The arrow syntax access this in a global scope. – Uriah Gray Sep 04 '21 at 03:30
  • `global` object in the browser is `window` object. When you use normal function then you get the reference of `window` of `this`. But what you need is that `this` should refer `vue` instance not `window.` – DecPK Sep 04 '21 at 03:32