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.
Seeing a lot of the above? If so this might be useful!
React Timeout is a higher order component for React and React Native providing the wrapped component with safe versions of
Set | Clear |
---|---|
setTimeout |
clearTimeout |
setInterval |
clearInterval |
setImmediate |
clearImmediate |
requestAnimationFrame |
cancelAnimationFrame |
When the wrapped component is unmounted, any lingering timers will be canceled automatically.
npm install --save react-timeout
import ReactTimeout from 'react-timeout'
From ^0.18
and onwards it just works.
For previous versions, import it like so:
import ReactTimeout from 'react-timeout/native'
This simulates a light switch that takes 5000ms
to switch between on
and !on
.
import ReactTimeout from 'react-timeout'
var Example = React.createClass({
toggleOn: function () {
this.setState({ on: !this.state.on })
},
handleClick: function (e) {
this.props.setTimeout(this.toggleOn, 5000)
},
render: function () {
return (
<button
style={{ backgroundColor: (this.state.on ? 'yellow' : 'gray') }}
onClick={this.handleClick}>Click me!</button>
)
}
})
export default ReactTimeout(Example)
Had we just called the regular old setTimeout
and unmounted the component, the callback would still fire and try setting the state of an unmounted component. However since we use ReactTimeout
the this.props.setTimeout
will get canceled the moment the component unmounts.
class Example extends Component {
render() {
return (
<button
onClick={() => this.props.setTimeout(..)}>Click me!</button>
)
}
}
export default ReactTimeout(Example)
const Example = ({ setTimeout }) => ({
<button
onClick={() => setTimeout(..)}>Click me!</button>
})
export default ReactTimeout(Example)
@ReactTimeout
class Example extends Component { .. }
@ReactTimeout
var Example = React.createClass({ .. })
The timer mixin recommended by the react-native docs.
Since the major version changed from 0
to 1
the only breaking change is dropping the reactTimeout
namespace.
For example: this.props.reactTimeout.setTimeout
becomes this.props.setTimeout
.