3

I have an app that read values from an external devices, then these values are written in a DB. When I wrote this data in the db I receive this error:

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.

And It is about this code:

this.setState(state => ({
          acc_dx,
          array_acc_dx: [...state.array_acc_dx, [timeagm, ...acc_dx].join(":")]
        }));

this code is a part of a function setupNotifications1 which in turn is called in a function called in the componentDidMount ().

How can I solve this warning? Thank you.

EDIT 1:

componentDidMount() {
    this.deviceService1(this.device1);
  }

Inside deviceService1() I call this.deviceService2(this.device2) and inside I call setupNotifications1(this.device1) and setupNotifications2(this.device2)

EDIT 2:

async setupNotifications1(device) {
    var timeagm = 0;
    var time = 0;
    const service = this.serviceGeneral();


    this.subscriptionMonitor1 = await device.monitorCharacteristicForService(
      service,
      this.AccGyrMg,
      (error, characteristic) => {
        if (error) {
          this.error(error.message);
          return;
        }

        const buf = Buffer.from(characteristic.value, "base64");
        const [...acc_dx] = [2, 4, 6].map(index => buf.readInt16LE(index));
        this.setState(state => ({
          acc_dx,
          array_acc_dx: [...state.array_acc_dx, [timeagm, ...acc_dx].join(":")]
        }));
        timeagm += 20;

then I have a stop button that is used to remove this.subscriptionMonitor1 and change page ( I pass the value in the other page where there are written in the DB )

Jack23
  • 1,368
  • 7
  • 32
  • Does this answer your question? [Setting state on componentDidMount()](https://stackoverflow.com/questions/35850118/setting-state-on-componentdidmount) – Oen44 Nov 21 '19 at 14:48
  • 1
    show the entire `componentDidMount` function – Brandon Nov 21 '19 at 14:50
  • @Oen44 No it's not :( – Jack23 Nov 21 '19 at 14:53
  • @Brandon I have edited the question – Jack23 Nov 21 '19 at 14:54
  • @Jack23 that still isn't really enough details. How long do these functions take, are they making API calls? If you unmount the component before the `setState` is able to happen, the functions will continue and this is where you'll see the error. – MattyK14 Nov 21 '19 at 17:00
  • show the entire call stack from the start of componentDidMount to when this.setState() is called. – Brandon Nov 21 '19 at 18:51
  • I Edit (2) my question :) – Jack23 Nov 22 '19 at 08:08
  • Does this answer your question? [Is there a way to check if the react component is unmounted?](https://stackoverflow.com/questions/39767482/is-there-a-way-to-check-if-the-react-component-is-unmounted) – dmitri7 Nov 22 '19 at 11:00

0 Answers0