mobxjs / mobx-state-tree

Full-featured reactive state management without the boilerplate
https://mobx-state-tree.js.org/
MIT License
6.94k stars 640 forks source link

How to cancel a flow function that contain api axios call #2009

Closed vantuan88291 closed 11 months ago

vantuan88291 commented 1 year ago

I have flow function like this:

  resetSignal: flow(function* () {
      const result = yield self.environment.api.service.resetSignal(self.itemServiceSelected.mainNo)
      if (result.kind === 'ok') {
        self.rootStore.commons.setLoading(false)
      } else {
        self.rootStore.commons.error(result.data)
      }
    }),

i want to cancel that function when component unmount, cuz that api need to wait for a long time. And i add abort like this:

  .actions(self => {
      addMiddleware(self, (call, next, abort) => {
        if (call.name === "resetSignal") {
          self.dispose = abort
        }
        next(call)
      })
      return {}
    })

and in my component will call this function:

React.useEffect(() => { return () => { model.dispose("cancel") } }, [])

but its not working, the api still call after component unmount. Have anyone have any ideal?

coolsoftwaretyler commented 1 year ago

Hey @vantuan88291 - I don't know if I have a great solution for you, but two thoughts:

  1. Can you write up a CodeSandbox to demonstrate what you're trying to do? That would make it a little easier for folks to tinker with code and help troubleshoot/propose solutions
  2. There is some old conversation around cancelling actions that might be relevant, but I don't know if there's a full solution there.
coolsoftwaretyler commented 1 year ago

I'm going to label this as has PR, because I think https://github.com/mobxjs/mobx-state-tree/pull/691 would be a solution, or close to. Leaving the issue open if/until we merge that in.

i-mighty commented 1 year ago

I'm going to label this as has PR, because I think #691 would be a solution, or close to. Leaving the issue open if/until we merge that in.

Safe to say this should be closed then?

coolsoftwaretyler commented 1 year ago

Hey @i-mighty - no, we closed that PR because it's been stale for a very long time and we're about to do some big reformatting here. The issue itself still stands. Here's the details on why we closed that PR: https://github.com/mobxjs/mobx-state-tree/pull/691#issuecomment-1729924874

If you are interested in closing this out, I'd love to review an up-to-date PR to that effect.

chakrihacker commented 11 months ago

Can we close this with this as workaround https://www.npmjs.com/package/mst-async-task ?

coolsoftwaretyler commented 11 months ago

@chakrihacker - yeah I feel fine about that! I think we decided to close it out and recommend the third-party solution for now. Good call.

Would be happy to review a PR implementing an integration if someone gets interested in it.