使用 websockets 接收消息时如何更改 componentDidMount() 中的状态?

How to change state inside componentDidMount() when recieving a message with websockets?

我收到了一条 websocket 消息。我想用这条消息改变我的组件的状态。当我尝试这样做时,出现错误。我该如何解决?

componentDidMount() {

    this.wsConnection.onmessage = function (eventInfo) {

        console.log("Message arrived from websocket: ", eventInfo.data);
        this.setState({team: eventInfo.data});
    };
}

我的错误:

TypeError: this.setState is not a function

你能试试下面的代码吗

this.wsConnection.onmessage = (eventInfo) => {

    console.log("Message arrived from websocket: ", eventInfo.data);
    this.setState({team: eventInfo.data});
};