React报错求助:Cannot update during existing state transition问题排查
Let's break down what's causing this warning and fix it step by step.
Why You're Seeing This Warning
The error happens because you're calling setState inside componentWillReceiveProps—in older React versions, this lifecycle hook can fire during an ongoing render/state transition process. When you update state mid-transition, React throws this warning to prevent unexpected behavior.
Worse yet, you're using a common React anti-pattern here: copying props to state unnecessarily. There's no need to sync appointment and responseObj from props into your component's state—you can use these values directly from props, which eliminates the state sync issue entirely.
Step-by-Step Fix
- Remove the problematic lifecycle hook: Delete the
componentWillReceivePropsmethod entirely—we don't need it anymore. - Use props directly in render: Replace all references to
this.state.appointmentandthis.state.responseObjwiththis.props.appointmentandthis.props.responseObj. - Clean up redundant state: If you initialized
appointmentandresponseObjin your component's constructor, remove those state fields too.
Modified Working Code
class SavedAppointments extends React.Component { render() { // Destructure values directly from props instead of state const { appointment, responseObj, userId } = this.props; let content = null; let message = null; if (appointment === null) { content = 'loading ...'; } else if (appointment === false) { if (responseObj) { if (responseObj.data.errno === 1062) { message = <div>appointment became unavailable. </div>; } } else { content = "no records "; } } if (responseObj && responseObj.data.errno === 1062) { message = "sorry, cannot reserve more than one appointment"; } if (appointment) { content = <SimpleMediaCard userId={userId} appointment={appointment} />; } return ( <div> {content} {message} </div> ); } } function mapStateToProps({ appointment, responseObj }, ownProps) { return { appointment, responseObj, userId: ownProps.userId // Pass userId directly from ownProps }; } export default connect(mapStateToProps, mapDispatchToProps)(SavedAppointments);
Key Improvements
- Eliminated unnecessary state sync, which removes the root cause of the warning
- Simplified component logic by using props directly (React will re-render automatically when props change)
- Cleaned up conditional logic with
else ifto avoid unintended overlap between checks
Note: If you're using React 16.3+, componentWillReceiveProps is deprecated anyway. Even if you needed derived state (which you don't here), the modern replacement is getDerivedStateFromProps—but in this case, relying directly on props is the best practice.
内容的提问来源于stack exchange,提问作者Abdulrhman Alsri

