0

This bug does not happen every time but it pops up enough to be a concern for my app. Currently, I have a container that handles all my HTTP requests and it does so by polling the server like so:

  componentDidMount(){
    this.timer = setInterval(() => [this.getData(), this.getCustData()], 1000);
  }

  componentWillUnmount(){
    this.timer && clearInterval(this.timer);
    this.timer = false
  }
  getData = () => {
      axios.get('http://localhost:3001/api/v1/pickup_deliveries')
        .then((response) => {
            this.setState({
              apiData: response.data
            })
          })
        .catch((error)=>{console.log(error);});
  }

I use React Router to go to another container that also utilizes HTTP request but that has nothing to do with the container that does the polling (I will be fixing this with redux shortly but I have not implemented it yet). Basically, the polling should (and does) cease when I unmount the component. The problem is, every now and then when I switch to the next component, I get an error in transition. It is like it's getting caught within one of the one second intervals and causing a brief memory leak.:

index.js:1437 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in PickupDeliveriesForm (created by Wrapper)
    in div (created by Wrapper)
    in Wrapper (at PickupDeliveries.js:200)
    in div (at PickupDeliveries.js:197)
    in div (at PickupDeliveries.js:196)
    in PickupDeliveries (created by Context.Consumer)

Is this a major concern? Should I worry about that random memory leak, or does that come with the territory when I am trying to unmount a component that is polling a server with setInterval?

AttemptedMastery
  • 738
  • 6
  • 21
  • You can add a flag to see if the component is mounted or not before calling setState https://stackoverflow.com/questions/58573988/random-memory-leak-error-when-switching-to-a-different-component-with-react-rout#58573988 – azium Oct 26 '19 at 19:38
  • Hey, thanks for the comment but you linked back to me thread. Do you have a thread link that shows a clean implementation of a flag? – AttemptedMastery Oct 26 '19 at 19:43
  • oh oops sorry about that here you go https://stackoverflow.com/questions/39767482/is-there-a-way-to-check-if-the-react-component-is-unmounted – azium Oct 27 '19 at 15:30
  • which links to the react docs about this topic https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html – azium Oct 27 '19 at 15:30

0 Answers0