score:0

You need to check if you component is mounted now. You can create trigger mounted in your state and manage it in lifecycles methods.

constructor(props) {
 super(props);
 this.state = { mounted: false };
}

componentDidMount() {
 this.setState({ mounted: true });
}

componentWillUnmount() {
 this.setState({ mounted: false });
}

componentWillReceiveProps(nextProps){
 if(this.props.totalVehicles !== nextProps.totalVehicles && 
  this.state.mounted){
   this.setState({animation: "cartCount"}, () => setTimeout(() =>
    this.setState({animation: null}), 1000));
 }
}

score:0

Instead of using state "mounted" try using instance variable "mounted":

constructor(props) {
 super(props);
 this.mounted = false;
}

componentDidMount() {
 this.mounted = true;
}

componentWillUnmount() {
 this.mounted = false;
}

componentWillReceiveProps(nextProps){
 if(this.props.totalVehicles !== nextProps.totalVehicles && 
  this.mounted){
   this.setState({animation: "cartCount"}, () => setTimeout(() =>
    this.setState({animation: null}), 1000));
 }
}

score:1

How about setting it on componentWillUpdate? That way, you know that the component has mounted already. Docs here

If you want to set up initial state, do it in componentWillMount.

More lifecycle methods in here

score:2

Although this is an old questions, i'll answer it for future references.

When using setState (which is asynchronous) via setTimeout, you have to remember to clear the timeout on componentWillUnmount. Otherwise, you might get to situations in which the setState is called after the element has already unmounted.


Related Query

More Query from same tag