facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
228.56k stars 46.79k forks source link

Bug: Why does React need to replay beginwork when an exception occurs #25041

Closed lizuncong closed 6 months ago

lizuncong commented 2 years ago

React version: React17.0.1

Sorry, I am curious why the beginWork function needs to be executed repeatedly if an exception is thrown in the beginWork function. In fact, we can simplify the exception catching logic of the beginWork function

Maybe this would work too

      let caughtError = null;

      function invokeGuardedCallback(func) {
        const evt = document.createEvent("Event");
        const evtType = "react-invokeguardedcallback";
        const fakeNode = document.createElement("react");
        let child; // keep the result of beginWork in the child variable

        function callCallback() {
          fakeNode.removeEventListener(evtType, callCallback, false);
          child = func(); // keep the result of func
        }

        function handleWindowError(event) {
          caughtError = event.error;
        }

        window.addEventListener("error", handleWindowError);
        fakeNode.addEventListener(evtType, callCallback, false);

        evt.initEvent(evtType, false, false);
        fakeNode.dispatchEvent(evt);

        window.removeEventListener("error", handleWindowError);
        return child; // return it
      }

      function beginWork() {
        return "child";
      }
      beginWork$1 = function (current, unitOfWork, lanes) {
        const child = invokeGuardedCallback(beginWork);
        if (hasCaughtError()) {
          var replayError = clearCaughtError();
          throw replayError;
        }
        console.log("next..", child);
        return child;
      };
      beginWork$1();
github-actions[bot] commented 6 months ago

This issue has been automatically marked as stale. If this issue is still affecting you, please leave any comment (for example, "bump"), and we'll keep it open. We are sorry that we haven't been able to prioritize it yet. If you have any new additional information, please include it with your comment!

github-actions[bot] commented 6 months ago

Closing this issue after a prolonged period of inactivity. If this issue is still present in the latest release, please create a new issue with up-to-date information. Thank you!