简体   繁体   中英

Uncaught TypeError: Cannot read property 'setState' of undefined with a function

Here's my code:

export type State = {hddstate: string, cpustate: string};
export type Properties = {};


export class SearchComponent extends React.Component<Properties, State> {
private inputTimer?: number;

constructor(properties: Properties) {
    super(properties);

    this.state = {
        hddstate: "turned off",
        cpustate: "turned off"

    };
}

public CpuStatus(): void {
    this.setState({hddstate: "turned off"});
    this.setState({cpustate: "turned on"});
}

When I call CpuStatus(), I get "Uncaught TypeError: Cannot read property 'setState' of undefined"

Why does this happen and how can I fix this?

In JavaScript, class methods are not bound by default.

You need to bind your method in the constructor. This can be done by adding the following line of code to your constructor: this.CpuStatus = this.CpuStatus.bind(this);

"If calling bind annoys you, there are two ways you can get around this." As @Murat suggested, "If you are using the experimental public class fields syntax, you can use class fields to correctly bind callbacks." - https://reactjs.org/docs/handling-events.html

You need to bind your function or this will be undefined eg with the fat arrow notation

public CpuStatus = (): void => {
    this.setState({ hddstate: "turned off" });
    this.setState({ cpustate: "turned on" });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM