0

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

  • 1
    I don't know vueJS, but your anonymous function is going to have a new value of `this` (which will almost certainly be the global object), hence the error. Use an arrow function instead of a `function() {..}` declaration (I see you use them elsewhere in this code) to keep the value of `this` the same as in the surrounding scope – Robin Zigmond Sep 13 '18 at 10:24
  • 2
    have you tried using arrow function? – William Chong Sep 13 '18 at 10:24
  • 1
    you must check what the "this" of ```this.sendStatus``` is referring to...try ```console.log(this)``` – ngakak Sep 13 '18 at 10:24
  • 1
    [How does the “this” keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). – Decade Moon Sep 13 '18 at 10:24
  • I replace the function for an arrow function, and It work correctly! Thanks for your fast response! – Miguel Herreros Cejas Sep 13 '18 at 10:29

2 Answers2

3

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

If you are using ES6, the easies 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.

wtfzn
  • 523
  • 5
  • 12
1

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

Thomas Lombart
  • 401
  • 2
  • 8