Javascript TypeError:无法读取属性';设置状态';未定义的

Javascript TypeError:无法读取属性';设置状态';未定义的,javascript,jquery,ajax,reactjs,this,Javascript,Jquery,Ajax,Reactjs,This,我试图在ajax回调从RESTAPI接收数据后设置组件的状态。下面是我的组件构造函数代码 constructor(props) { super(props); this.state = { posts: [] }; this.getPosts = this.getPosts.bind(this); } 然后我有一个componentDidMount方法,如下所示 componentDidMount() { this.getPosts(); } 现在是我

我试图在ajax回调从RESTAPI接收数据后设置组件的状态。下面是我的组件构造函数代码

constructor(props) {
    super(props);
    this.state = { posts: [] };
    this.getPosts = this.getPosts.bind(this);
}
然后我有一个
componentDidMount
方法,如下所示

componentDidMount() {
        this.getPosts();
}
现在是我的getPosts函数,我在这里执行ajax请求

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState( { posts: data } )
        }
    });
}
我正在尝试设置状态,但出现以下错误

this.setState is not a function

我不确定是什么原因造成的。如果有人给我指出正确的方向,那将非常有帮助。提前感谢。

这个问题与失去上下文有关。 请试试这个:

let self = this;
getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            self.setState( { posts: data } )
        }
    });
}
也可以使用绑定:

getPosts = () =>  {
        $.ajax({
            type: 'get',
            url: urlname,
            success: function(data) {
                self.setState( { posts: data } )
            }
        });
    }.bind(this)

同时绑定回调函数,以便回调中的
指向React组件的上下文,而不是回调函数

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: (data) => {
            this.setState( { posts: data } )
        }
    });
}
或者你可以用bind,比如

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState({ posts: data })
        }.bind(this)
    });
}

您必须将上下文存储到变量中,因为“this”引用在回调中不可用。尝试以下解决方案:

getPosts = () =>  {
let that=this;
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            that.setState( { posts: data } )
        }
    });
}

没问题,很高兴能帮上忙。这是大多数人常犯的错误。我将建议您在将来遇到此类错误时研究绑定