29

I am setting a listener in my application and using force update whenever it is broadcasted but it gives error forceUpdate cant be called on unmounted component. How can I check if a component is mounted now that the isMounted() function is deprecated.

'use strict';
var React = require('react-native');
import ExpAndroid from './ExpAndroid';
var {
  AppRegistry,
  Image,
  ListView,
  TouchableHighlight,
  StyleSheet,
  Text,
  View,
  Component,
  AsyncStorage,
  Navigator,
  DeviceEventEmitter
} = React;

var rowID;
var img=require('./resource/ic_pause_white.png');





class Example1 extends Component{
  constructor(props) {
    super(props);
    this.state = {

    };
  }
  componentWillMount(){

      rowID = this.props.rowIdentity;
      console.log("rowID "+rowID);

  }


componentDidMount(){
  console.log('component  mounted')
  this.start();

  DeviceEventEmitter.addListener('playMusicStatus', (data)=> {


   if(data.playMusic==true){

     img=require('./resource/ic_pause_white.png');
       rowID++;
        this.setState(this.state);
        ExpAndroid.someMethod1("someurl);


  }



});
}

componentWillUnmount(){
  console.log('componentwill  unmounted')
}

  start() {

    var  url = "some url";
    ToastAndroid.prepareToPlay(url,true);
}



render() {




     return (
      <Image source={require('./resource/album_back.png')} style={styles.background}>
      <Image
      source={{uri:this.state.trackDetails[rowID].thumnail_loc}}
      style={styles.thumbnail}
      />
      <View style={styles.flowRow}>
      <Text
      style={styles.titles}
      >text1 + {rowID}: </Text>
      <Text
      style={styles.titles}
      >{this.state.details[rowID].text1}</Text>
      </View>
      <View style={styles.flowRow}>
      <Text
      style={styles.titles}
      >text2 : </Text>
      <Text
      style={styles.titles}
      >{this.state.details[rowID].text2}</Text>
      </View>
      <View style={styles.flowRow}>
      <Text
      style={styles.titles}
      >Text3 : </Text>
      <Text
      style={styles.titles}
      >{this.state.Details[rowID].Text3}</Text>
      </View>
      <View style={styles.flowRow}>
      <Text
      style={styles.titles}
      >Text4 : </Text>
      <Text
      style={styles.titles}
      >{this.state.details[rowID].Text4}</Text>
      </View>


      </Image>
    );
  }
}
var styles = StyleSheet.create({

  container: {
    flex: 1,

  },
  background: {
    flex: 1,

    width: null,
    height: null,
  },

  flowRow : {
    flexDirection :'row',

  },
  flowRowPlay : {
    flexDirection :'row',
    alignSelf:'center',

  },
  backgroundImage: {
    flex: 1,
    resizeMode: 'cover', // or 'stretch'
  },

  thumbnail: {
    width: 100,
    height: 120,
    alignSelf:'center',
    margin :30
  },

  controls: {
    width: 30,
    height: 30,
    margin:20
  },


  titles: {
    fontSize: 15,
    margin:20,
    color: 'white',

  },
  timings: {
    fontSize: 12,
    margin:5,
    color: 'white',

  },
});

module.exports = Example1;

3 Answers 3

60

You can handle this yourself in your component:

componentDidMount() { 
  this._mounted = true;
}

componentWillUnmount() {
  this._mounted = false;
}

Then you can check the value of this._mounted in your listener.

Please note that using forceUpdate() should be avoided https://facebook.github.io/react/docs/component-api.html#forceupdate

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your component "pure" and your application much simpler and more efficient.

5
  • 1
    In my case componentWillUnmount() is not called . I have registered my event at native side and listening to it in react in componentDidMount.And whenever it receives that listener it calls the setstate to update the view. May 30, 2016 at 11:03
  • If componentWillUnmount why would you need to know if it's unmounted?
    – Moti Azu
    May 30, 2016 at 11:09
  • I have updated the code,everytime I receive the listener I update the rowId by 1 and call setState on it,but in my case it gives me error cannot update the unmounted state and by the time row id gets incremented by 2 or 3 and then state is set. May 30, 2016 at 11:27
  • 2
    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. May 30, 2016 at 11:33
  • how should we avoid this ? Apr 20, 2018 at 10:27
1

What I did was changing the callback in componentWillMount.

let asyncCallback;

componentDidMount(){
    asyncCallback = res=> this.setState({data: res});
    asyncTask(asyncCallback);
}

componentWillUnmount(){
    asyncCallback = ()=> console.log("AsyncCallback called but component has unmounted");
}
1

Using ReactUpdateQueue, you can avoid managing your own isMounted state.

const ReactUpdateQueue = require('ReactUpdateQueue');

// Pass the ref to your component.
if (ReactUpdateQueue.isMounted(view)) {
  // Your component is mounted!
}
2
  • 6
    @ThomasKekeisen This solution broke when React started using Fiber.
    – aleclarson
    Nov 6, 2017 at 1:03
  • Yes, it's an antipattern now - isMounted antipattern
    – Ihor
    Feb 22, 2018 at 12:53

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.