Miguel Herreros Cejas
Miguel Herreros Cejas

Reputation: 674

Problem with Scope Functions in Method from Vue.js

I have a SetInterval inside to a Promise in Axios. When I try to execute a function in this SetInterval, I have the follow error:

    methods: {
    getJson() {
        axios.post(url, FormObject, config)
        .then(response => {
        var searchId = JSON.stringify(response.data.searchId)
        this.sendStatus(searchId)
        var status = setInterval(function(){ this.sendStatus(searchId) }, 
         30000);
        })
        .catch(err => (this.error = err))

      },

      sendStatus(searchId){},

     }

The first call (this.sendStatus(searchId)) working correctly. However, the setInterval return this error:

Uncaught TypeError: this.sendStatus is not a function at eval

Upvotes: 0

Views: 1228

Answers (2)

wtfzn
wtfzn

Reputation: 538

You are changing the context of this in your second call, as you are introducing a new function.

If you are using ES6, the easiest way to overcome this, is to use an arrow function instead of the function keyword.

    var status = setInterval(() => { this.sendStatus(searchId) }, 
      30000);
    })

If you cannot use ES6, you have to use the .bind() function, which is explained in this question. Easier, but dirtier would be to reassign this to a local variable.

var that = this;

Then use that.sendStatus in your callback function.

Upvotes: 3

Thomas Lombart
Thomas Lombart

Reputation: 433

You need to use an arrow function in your setInterval, like this :

setInterval(() => this.sendStatus(searchId))

Here is a resource explaining more the arrow functions and this

Upvotes: 1

Related Questions