Ad

React Uncaught TypeError: This.setState Is Not A Function

- 1 answer

This is my first React code. I am trying to call a Restful web services from React. It kept saying "Uncaught TypeError: this.setState is not a function". I couldn't figure out what's wrong with the code.

<!DOCTYPE html>
<html>
    <head>
        <title>React Flux</title>
        <script src="https://fb.me/react-0.13.3.js"></script>
        <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
        <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>
    <body>
        <div id="component"></div>

        <script type="text/jsx">

            var JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/rest/user/456"
                    }).then(function(data) {
                        this.setState({text: data.name});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });

            React.render(<JavaEEWSTest />, document.getElementById('component'));
        </script>
    </body>
</html>
Ad

Answer

You need set this to callback function

$.ajax({
  url: "http://localhost:8080/rest/user/456"
}).then(function(data) {
 this.setState({text: data.name});
}.bind(this))
^^^^^^^^^^^

but not for $.ajax/then - }).bind(this)

Ad
source: stackoverflow.com
Ad