Axios ReactJS - 无法读取未定义的 属性 'setState'

Axios ReactJS - Cannot read property 'setState' of undefined

我在 ReactJS 中做一件简单的事情时遇到错误 "TypeError: Cannot read property 'setState' of undefined"。我正在尝试使用 axios 用响应数据填充输入。到目前为止没有成功。 我对 axios 和 ReactJs 都很陌生,所以它可能是我忽略的非常简单的东西?

我希望 "RESPONSE TEXT" 在 TypeError 修复后显示在表单的输入字段中。

这是我的组件:

class BasicInfoBlock extends React.Component {
    constructor(props) {
        super(props);

        this.state = { name : "EventTestName" };
    }

    componentDidMount() {
        axios
        .get(getBaseUrl()+`get`)
        .then(function (response) {
            this.setState({name: "RESPONSE TEXT"});
            //this.setState({name: response.data.name});
        })
        .catch((e) => 
        {
            console.error(e);
        });
        //this.setState({});
    }


    render(){
        return(
                <form className="form-horizontal">
                    <div className="form-group">
                        <label htmlFor="eventName" className="col-sm-2 control-label">Name</label>
                        <div className="col-sm-10">
                        <input type="text" id="eventName" className="form-control" placeholder="Event name" defaultValue={this.state.name}/>
                        </div>
                    </div>
                </form>
            );
    }
}

感谢您的帮助

编辑:这不是一个重复的问题,这个问题与 'this' 在回调中不可用有关。被选为重复的问题与绑定有关。

在您的 Promise 的 then 方法中,this 将不再引用该组件。您可以使用这样的箭头函数来修复:

componentDidMount() {
  axios
  .get(getBaseUrl()+`get`)
  .then((response) => {
    this.setState({name: "RESPONSE TEXT"});
    //this.setState({name: response.data.name});
  })
  .catch((e) => 
  {
    console.error(e);
  });
  //this.setState({});
}