this.IsMounted() is not a function
I'm trying to build a simple React App. It retrieves data from an ajax call and renders it to the page. The issue I'm having it setting the state of this.props after the ajax call. I'm receiving this error:
Uncaught TypeError: this.isMounted is not a function
I've been going through tutorials and looking at some example code, like this page on loading information through ajax on the react site https://facebook.github.io/react/tips/initial-ajax.html, but I don't see what would be causing this error. Here's my code:
var ANiceReminderApp = React.createClass({ getInitialState: function(){ return { quotes: [] }; }, componentDidMount: function(){ $.ajax({ headers: { 'X-Mashape-Key':'xxxxxx'}, url: 'https://healthruwords.p.mashape.com/v1/quotes/', type: 'GET', dataType: 'JSON', success: function(data){ var quote = data[0].media; if(this.isMounted()){ this.setState({ quotes: quote }); } } }); }, render: function() { return ( <div className="container"> hello world <img src={this.state.quotes}/> <button>Need more inspiration?</button> </div> ); } }); React.render(<ANiceReminderApp />, document.body);
2 Answers
@gilly3's answer explains the issue. However, I prefer a different solution: React will efficiently auto-bind class methods, meaning that this
will refer properly to the instance. So I generally use methods as callbacks:
React.createClass({ componentDidMount: function(){ $.ajax({ // the method is already bound to the component success: this.onDataReceived }); }, onDataReceived: function(data) { var quote = data[0].media; if(this.isMounted()){ this.setState({ quotes: quote }); } }, // ... });
This has a couple of advantages:
-
In theory at least, React's binding is more efficient than using
.bind
. This is particularly true if you'd have to call.bind
repeatedly for multiple calls. -
It makes the callback more easily testable on its own.
-
It makes it easier to invoke the callback logic through some other code path (e.g. if you also want to accept data provided via
props
).
It's also worth seeing this discussion, which suggests that isMounted
may be deprecated in the future - the suggested path in this case is to save a reference to the AJAX request and abort it on componentWillUnmount
.
In event handlers, this
refers to the object that raised the event. In your case, that would be the jqXHR
object, which indeed lacks the .isMounted()
method.
To deal with this situation you need to either keep a reference to the outer this
and use that reference within the event handler, or use function.bind()
to force the function to retain the outer context.
Here is an example of how to do the latter method:
$.ajax({ ... success: function(data) { var quote = data[0].media; if (this.isMounted()){ this.setState({ quotes: quote }); } }.bind(this); // Note the use of .bind(this) here });
转载:http://stackoverflow.com/questions/31575516/this-ismounted-is-not-a-function