0

I have form where I should render one of elements in a while. I use setTimeout for this aim in componentDidMount but I get warning setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

class Form extends React.Component {
    constructor(props, context) {
        this.state = {resend: false};
    }

    componentDidMount() {
        const max = 3;

        if (this.props.count < max) {
            setTimeout(() => {
                this.setState({resend: true});
            }, 1000);
        }
    }

    render() {
        return (
            <form>
                ...
                {this.state.resend ? <Component/> : null}
            </form>
        );
    }
}

2 Answers 2

2

Your component is probably unmounting at some point, then the timeout finishes, and it attempts to call setState after your component is no longer being rendered.

You need to cancel any timeouts you have running in componentWillUnmount. Store a reference to them and delete them.

class Form extends React.Component {
    constructor(props, context) {
        this.state = {resend: false};
        this.timeouts = [];
    }

    componentWillUnmount(props, context) {
        this.timeouts.forEach(t => window.clearTimeout(t));
    }

    componentDidMount() {
        const max = 3;

        if (this.props.count < max) {
            const timeoutId = setTimeout(() => {
                this.setState({resend: true});
            }, 1000);
            this.timeouts.push(timeoutId);
        }
    }

    render() {
        return (
            <form>
                ...
                {this.state.resend ? <Component/> : null}
            </form>
        );
    }
}
0
0

This might be because the component doesn't exist when the setTimeout calls. Use a mounted flag to see if the component still exists.

constructor(props, context) {
  this.state = {resend: false};
  this.mounted = true;
}

componentWillUnmount() {
  this.mounted = false;
}

componentDidMount() {
  const max = 3;

  if (this.props.count < max) {
    setTimeout(() => {
      if (!this.mounted) return;
      this.setState({resend: true});
    }, 1000);
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.