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

ReactJS Cannot read property setState of undefined

我是ReactJS的新手,有点理解这个问题在SOF中是重复的数字问题。

但我希望有人能给我一些指导和澄清一些 React 的概念。

我想做的只是在加载屏幕之前使用 axiosisomorphic-fetch 从远程 REST API 获取数据。

但是看了很多类似的React教程,还是没看懂。

这是我的代码:

import React, { Component } from 'react';
import axios from 'axios'

// import InputRow from './components/InputRow';
import './App.css';

// require('es6-promise').polyfill();
// require('isomorphic-fetch');

class App extends Component {

 constructor(props) {
  super(props);

  const app_id = '<my_app_id>';

  const version = 0.1;
  this.luisURL = `https://westus.api.cognitive.microsoft.com/luis/api/v2.0/apps/${app_id}/versions/${version}`;

  // this.getLUISIntent = this.getLUISIntent.bind(this);

  this.state = {
   intentOptions: [],
   utterance: '',
   intent: ''
  };
 }

 getLUISIntent = () => {
  const subscription_key = '<my_subscription_key>';

  const URL = this.luisURL + '/intents';

  return axios.get(URL, {
   headers: {
    "Content-Type": 'application/json',
    "Ocp-Apim-Subscription-Key": subscription_key
   },
  })
  .then(function(res){
   this.setState({intentOptions: res.data});
  });
 }

 componentWillMount = () => {
  // this.setState({
  //  intentOptions: this.getLUISIntent()
  // });
 }

 componentDidMount = () => {
  this.getLUISIntent();
 }

 componentDidUpdate = (prevProps, prevState) => {
  console.log("state: ", this.state);
  // this.submitToLUIS();
 }

 shouldComponentUpdate = (nextProps, nextState) => {
  return true;
 }

 submitToLUIS = () => {
  console.log("Submit to LUIS: ", this.state);
 };

 setIntent = (e) => {
  this.setState({intent: e.target.value});
 };

 setUtterance = (e) => {
  this.setState({utterance: e.target.value});
 };

 render() {
  return (
   <div className="App">
    <div className="container">
     <div className="row">
      <div className="col-sm-4">Utterance</div>
      <div className="col-sm-4">Intent</div>
      <div className="col-sm-4"></div>
     </div>
     <div className="row">
      <div className="col-sm-4">
       <input className="form-control utterance" type="text" onChange={this.setUtterance} />
      </div>
      <div className="col-sm-4">
       <select className="form-control intent" onChange={this.setIntent}>
        <option key="intent_defualt" value="">Select...</option>
        {this.state.intentOptions.map((obj, i) =>
         <option key={obj.id} value={obj.id}>{obj.name}</option>
        )}
       </select>
      </div>
      <div className="col-sm-4">
       <button className="btn btn-primary" onClick={this.submitToLUIS}>Create</button>
      </div>
     </div>
    </div>
        </div>
     );
   }
}

export default App;

这是我的问题:

非常感谢您的帮助。

您来自 ajax 请求的回调函数未绑定。当你将一个函数传递给另一个函数(作为回调)时,"this" 将是对它最终被调用时所在上下文的引用,而不是你编写它时的上下文。如果您使用箭头函数,它将保留您编写它时的上下文。

.then(function(res){
        this.setState({intentOptions: res.data});
    });

如果将此函数设为箭头函数,问题应该可以解决。

.then((res) => this.setState({intentOptions: res.data}));