如何解决 React 中 App.js 报错 Uncaught TypeError: Cannot read properties of undefined

在 React 开发过程中,经常会碰到一些报错。这里我们来看一个错误,是在 App.js 中报出来的。错误是这样的:App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading ‘setState’) at onInputChange (App.js:69:1)

下面是产生错误的完整的代码

// 调用 clarifai api接口
const app = new Clarifai.App({
    apiKey : 'a2013154seuiasdfdse94302c5bd'
});

class App extends  React.Component {
    constructor () {
        super();
        this.state = {
            input : '',
            imageUrl : '',
        }
    }

    onInputChange(event) {
        this.setState({input: event.target.value})
        console.log('setState input' + this.state.input);
    }

    onButtonSubmit() {
        this.setState({imageUrl: this.state.input});
        app.models.predict(Clarifai.COLOR_MODEL, this.state.input).then(
            function(response) {
                console.log(response);
            },
            function(err) {
                // 这里处理错误
            }
        )
    }
    render(){
        return (
            <div className="App">
                <Particles className="particles" id="tsparticles" options={particlesOptions} />
                <Navigation />
                <Logo />
                <Rank />
                <ImageLinkForm onInputChange={this.onInputChange} onButtonSubmit = {this.onButtonSubmit} />
                <FaceRecognition imageUrl = {this.state.imageUrl} />
            </div>
        );
    }
}

export default App;

解决这个问题的方法很少。

至于为什么会出现这种情况是因为在上面的代码中没有使用箭头方式,这里我们有两种解决方式

  1. 我们需要对处理程序进行绑定。如下所示
    constructor() {
    ...code
    this.onInputChange = this.onInputChange.bind(this)
    this.onButtonSubmit = this.onInputChange.bind(this)
    }
    
  2. 将方法改为箭头的方式(ES6 语法)。
    onInputChange = (event) => {
    this.setState({input: event.target.value})
    console.log('setState input' + this.state.input);
    }
    onButtonSubmit = () => {
    this.setState({imageUrl: this.state.input});
     app.models.predict(Clarifai.COLOR_MODEL, this.state.input).then(
         function(response) {
             console.log(response);
         },
         function(err) {
             // 这里处理错误
         }
     )
    }
    

我们可以选择上面两种方式中的任一种。排除各自的环境因素,都可以解决上面的报错。