I solved this by assigning a ref to the component and then checking if the ref exists before setting the state:
myMethod(){
if (this.refs.myRef)
this.setState({myVar: true});
}
render() {
return (
<div ref="myRef">
{this.state.myVar}
</div>
);
}
And lately, since I am using mostly functional components, I am using this pattern:
const Component = () => {
const ref = React.useRef(null);
const [count, setCount] = React.useState(0);
const increment = () => {
setTimeout(() => { // usually fetching API data here
if (ref.current !== null) {
setCount((count) => count + 1);
}
}, 100);
};
return (
<button onClick={increment} ref={ref}>
Async Increment {count}
</button>
);
};