useReducer 的 dispatch 被错误地调用了顺序。

huangapple go评论67阅读模式
英文:

useReducer dispatch called in a wrong order

问题

我正在编写一个钩子,应该帮助我处理异步 promises。现在我遇到了一个非常奇怪的问题。基本上,我以特定顺序两次调用 dispatch,并使用两个动作("actionA" 和 "actionB")。一个动作("actionA")在 useEffect 清理回调中被调用。我期望它的工作方式是这样的:"state1" -> "actionA" -> "state2" -> "actionB" -> "state3"。但实际上我得到的是一些像这样的东西:"state1" -> "actionB" -> "unexpected state 4","state1" -> "actionA" -> "state2"。

我附上了这个问题的完整工作示例。点击按钮两次,我得到的日志如下:

reducer cancelled(10) start(8) pending(11)
dispatch cancel 8
dispatch reject 8
reducer pending(11) reject(8) rejected(15)
reducer pending(11) cancel(8) cancelled(17)
reducer cancelled(17) start(13) pending(18)

所以很明显 dispatch cancel 8dispatch reject 8 的调用顺序是正确的。但是我期望的是获得类似 reducer pending(11) cancel(8) cancelled(17)cancelled(17) reject(8) cancelled(17) 这样的结果,但我得到的是这些 dispatches 以错误的顺序出现,它们作用于相同的状态!就好像它们在分叉状态一样。我不明白为什么会发生这种情况。组件本身没有卸载。在状态更改方面,useEffect 清理函数有什么特殊之处吗?

英文:

I'm writing a hook which is supposed to help me with async promises. Now I stumbled upon a very weird issue. Basically I call dispatch twice with two actions ("actionA" and "actionB") in a specific order. One action ("actionA") is called in a useEffect cleanup callback. I expect it to work like this: "state1" -> "actionA" -> "state2" -> "actionB" -> "state3". But instead I'm getting something like "state1" -> "actionB" -> "unexpected state 4", "state1" -> "actionA" -> "state2".

I attach full working example to this question. Click button twice. I'm getting logs like

reducer cancelled(10) start(8) pending(11)
dispatch cancel 8
dispatch reject 8
reducer pending(11) reject(8) rejected(15)
reducer pending(11) cancel(8) cancelled(17)
reducer cancelled(17) start(13) pending(18)

So it's clear that dispatch cancel 8 and dispatch reject 8 are called in a correct order. But instead of getting something like reducer pending(11) cancel(8) cancelled(17), cancelled(17) reject(8) cancelled(17) like I expected, I'm getting those dispatches in a wrong order and they act on the same state! It's like they fork the state. I don't understand why is this happening. Component itself is not unmounting. Is there something special about useEffect cleanup function in regards to state change?

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot; /&gt;
    &lt;title&gt;Test&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;
    &lt;script
      crossorigin
      src=&quot;https://unpkg.com/@babel/standalone@7/babel.js&quot;
    &gt;&lt;/script&gt;

    &lt;script
      crossorigin
      src=&quot;https://unpkg.com/react@18/umd/react.development.js&quot;
    &gt;&lt;/script&gt;
    &lt;script
      crossorigin
      src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.development.js&quot;
    &gt;&lt;/script&gt;
    &lt;script type=&quot;text/babel&quot;&gt;
      const { useEffect, useReducer } = React;
      const { createRoot } = ReactDOM;

      const rootElement = document.getElementById(&quot;root&quot;);
      createRoot(rootElement).render(&lt;App /&gt;);

      function App() {
        const [param, setParam] = React.useState(1);

        const result = usePromise(
          (signal) =&gt; {
            return myFetch(param, signal);
          },
          [param]
        );

        const handleClick = () =&gt; {
          setParam((param) =&gt; param + 1);
        };

        return (
          &lt;&gt;
            &lt;div&gt;param: {param}&lt;/div&gt;
            &lt;div&gt;result: {JSON.stringify(result)}&lt;/div&gt;
            &lt;button onClick={handleClick}&gt;click&lt;/button&gt;
          &lt;/&gt;
        );
      }

      function myFetch(param, signal) {
        return new Promise((resolve, reject) =&gt; {
          const timeoutId = setTimeout(() =&gt; {
            resolve(`result ${param}`);
          }, 1000);
          signal.addEventListener(&quot;abort&quot;, () =&gt; {
            clearTimeout(timeoutId);
            reject(&quot;aborted&quot;);
          });
        });
      }

      let nextId = 1;

      function reducer(state, action) {
        const id = nextId++;
        let nextState = state;
        switch (action.type) {
          case &quot;start&quot;:
            if (state.status === &quot;created&quot; || state.status === &quot;cancelled&quot;) {
              nextState = {
                id,
                promiseId: action.promiseId,
                status: &quot;pending&quot;,
              };
            }
            break;

          case &quot;resolve&quot;:
            if (
              state.status === &quot;pending&quot; &amp;&amp;
              state.promiseId === action.promiseId
            ) {
              nextState = { id, status: &quot;fulfilled&quot;, value: action.value };
            }
            break;

          case &quot;reject&quot;:
            if (
              state.status === &quot;pending&quot; &amp;&amp;
              state.promiseId === action.promiseId
            ) {
              nextState = { id, status: &quot;rejected&quot;, reason: action.reason };
            }
            break;

          case &quot;cancel&quot;:
            nextState = { id, status: &quot;cancelled&quot; };
        }

        console.log(
          &quot;reducer&quot;,
          `${state.status}(${state.id})`,
          `${action.type}(${action.promiseId})`,
          `${nextState.status}(${nextState.id})`
        );

        return nextState;
      }

      function usePromise(promiseFunction, deps) {
        const [state, dispatch] = useReducer(reducer, {
          id: nextId++,
          status: &quot;created&quot;,
        });
        useEffect(() =&gt; {
          const promiseId = nextId++;
          const abortController = new AbortController();
          const promise = promiseFunction(abortController.signal);
          dispatch({ type: &quot;start&quot;, promiseId });
          promise.then(
            (value) =&gt; {
              dispatch({ type: &quot;resolve&quot;, promiseId, value });
            },
            (reason) =&gt; {
              console.log(&quot;dispatch reject&quot;, promiseId);
              dispatch({ type: &quot;reject&quot;, promiseId, reason });
            }
          );
          return () =&gt; {
            console.log(&quot;dispatch cancel&quot;, promiseId);
            dispatch({ type: &quot;cancel&quot;, promiseId });
            abortController.abort();
          };
        }, deps);
        return state;
      }
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

答案1

得分: 1

这里的问题是 useEffect 的清理函数是异步调用的,在组件已经重新渲染并且第二个 dispatch 已经被调用之后。

我们可以在 usePromise 钩子中使用 useRef 来跟踪组件是否仍然挂载,并在清理函数中在调用第二个 dispatch 之前检查该值。

function usePromise(promiseFunction, deps) {
  const [state, dispatch] = useReducer(reducer, {
    id: nextId++,
    status: "created",
  });
  const promiseRef = useRef(null);
  useEffect(() => {
    const promiseId = nextId++;
    const abortController = new AbortController();
    const promise = promiseFunction(abortController.signal);
    promiseRef.current = promiseId;
    dispatch({ type: "start", promiseId });
    promise.then(
      (value) => {
        if (promiseRef.current === promiseId) {
          dispatch({ type: "resolve", promiseId, value });
        }
      },
      (reason) => {
        if (promiseRef.current === promiseId) {
          console.log("dispatch reject", promiseId);
          dispatch({ type: "reject", promiseId, reason });
        }
      }
    );
    return () => {
      console.log("dispatch cancel", promiseId);
      if (promiseRef.current === promiseId) {
        dispatch({ type: "cancel", promiseId });
      }
      abortController.abort();
    };
  }, deps);
  return state;
}
英文:

the problem here is the useEffect cleanup function being called asynchronously, after the component has already re-rendered and the second dispatch has already been called.

We can use useRef on the usePromise hook to keep track of whether the component is still mounted, and check that value in the cleanup function before calling the second dispatch.

function usePromise(promiseFunction, deps) {
  const [state, dispatch] = useReducer(reducer, {
    id: nextId++,
    status: &quot;created&quot;,
  });
  const promiseRef = useRef(null);
  useEffect(() =&gt; {
    const promiseId = nextId++;
    const abortController = new AbortController();
    const promise = promiseFunction(abortController.signal);
    promiseRef.current = promiseId;
    dispatch({ type: &quot;start&quot;, promiseId });
    promise.then(
      (value) =&gt; {
        if (promiseRef.current === promiseId) {
          dispatch({ type: &quot;resolve&quot;, promiseId, value });
        }
      },
      (reason) =&gt; {
        if (promiseRef.current === promiseId) {
          console.log(&quot;dispatch reject&quot;, promiseId);
          dispatch({ type: &quot;reject&quot;, promiseId, reason });
        }
      }
    );
    return () =&gt; {
      console.log(&quot;dispatch cancel&quot;, promiseId);
      if (promiseRef.current === promiseId) {
        dispatch({ type: &quot;cancel&quot;, promiseId });
      }
      abortController.abort();
    };
  }, deps);
  return state;
}

huangapple
  • 本文由 发表于 2023年2月27日 15:32:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75577771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定