React Native cancel animation delay when component will unmount


March 2019


1.3k time


I've a little problem with an animation. I try to do a Flash Bar Info on my app for the errors. So to do that I create a new component, this component can be place in one specific view or not, and when the error is trigger from my store the state of my component is change by componentWillReceiveProps and set to visible if there is an error message.

So, if there isn't an error message my render function return false value but if there is an error message I run my render function with this animation code:

// Ease in ease out anitmation
  Animated.timing(this.state.translateY, {
    toValue: 40,
    easing: Easing.bounce, // Like a ball
    duration: 450,
  Animated.timing(this.state.translateY, {
    toValue: 0,
    duration: 300,
]).start(() => {
  this.setState({ visible: false }); // <-- Problem is here

If I stay on my view during the animation delay, that's work perfectly, but if I go to my previous view when the message is set to visible, the function setState is called when my component is not mounted. So I got this waring:

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.

It's a normal behavior because the component is not mounted at this point. So, I try to find a way to cancel my animation sequence when the component will unmount.

During my research I find a temporary way by using setTimeout() function with clearTimeout when the component will unmount, but I can't find how to do that with Animated.delay function in an Animated.sequence, is it possible ?

In advance thank you for your answers!


It is possible to cancel an animation delay when component will unmount ?

1 answers


Функция вы отдаете Animated.start()вызывается с объектом объявляя ли запускали анимации до конца успешно. Реагировать-Native также неявно отменяет анимацию , если компонент демонтирован. Так проверьте finished-свойство в вашем функции обратного вызова, и только setStateесли анимация побежала к концу.

Таким образом, это должно работать:


]).start((done) => {
  if (done.finished) {
    this.setState({ visible: false });

(Обратите внимание , что если вы вручную остановить анимацию, используя , например , Animated.stop()или запустив анимацию , с тем же Animated.Value, то finished-property также тогда false.)