59

From the reactjs tutorial, what's the purpose of having .bind(this) at the end of the ajax callback? Does code work correctly without it?

        data: JSON.stringify({text: text}),
        success: function (data) {
            this.setState({data: data});
        }.bind(this),
ferk86
  • 2,325
  • 1
  • 23
  • 27
  • Something similar [here](http://stackoverflow.com/questions/33973648/react-this-is-undefined-inside-a-component-function). Without `.bind(this)` the `this` reference becomes null when used inside a custom function (defined in a reactJs component) . – RBT Apr 30 '17 at 06:44

2 Answers2

57

It ensure's this will be the correct object inside the callback. See Function.prototype.bind().

An alternative specific to react is to do:

myAjaxFunction: function(){
  $.getJSON('/something', this.handleData);
},
handleData: function(data){
  this.setState({data: data});
}

This works because React handles binding of component methods for you.

If you ran your original code in without bind, you'd get this error: TypeError: undefined is not a function because this === window in the callback;

or in strict mode: TypeError: Cannot read property 'setState' of undefined, where this === undefined in the callback.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • The part "specific to React" is possible because of autobinding added in 0.4: [Autobind by Default](https://facebook.github.io/react/blog/2013/07/02/react-v0-4-autobind-by-default.html). – Ross Allen Jun 18 '14 at 15:39
  • 4
    Also found this handy article explaining the use cases for the bind, apply, and call methods - http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ – Atlas7 Apr 14 '16 at 19:48
2

The purpose of having .bind(this) at the end of the ajax callback is let this be related to your react class. In other words you can add:

var self = this;

outside of ajax and it works the same. You code equal to:

var self = this;
$.ajax({
    .
    .
    data: JSON.stringify({text: text}),
    success: function (data) {
        self.setState({data: data});
    },
    .
    .
});
ChaosPredictor
  • 3,777
  • 1
  • 36
  • 46