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

1 Answer 1

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);
  },
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.