software-mansion / react-native-screens

Native navigation primitives for your React Native app.
https://docs.swmansion.com/react-native-screens/
MIT License
3.1k stars 521 forks source link

UIViewControllerHierarchyInconsistency #944

Closed yberstad closed 3 years ago

yberstad commented 3 years ago

Description

The app has been inactive for around 2 min on a "enter pin code page" leading to that the iPhone has been locked. If the user then unlocks the phone, enter the pin code and press the login button, the app then crashes.

After setting enabledScreen(false), I have not been able to reproduce a crash.

Exception from Bugsnag:

UIViewControllerHierarchyInconsistency: child view controller:<RNScreensViewController: 0x126d2ce00> should have parent view controller:(null) but actual parent is:<UIViewController: 0x125e2a7d0>

0  CoreFoundation   ___exceptionPreprocess
1  libobjc.A.dylib  _objc_exception_throw
2  CoreFoundation   +[NSException raise:format:]
3  UIKitCore        -[UIView(Hierarchy) _associatedViewControllerForwardsAppearanceCallbacks:performHierarchyCheck:isRoot:]
4  UIKitCore        -[UIView(Hierarchy) _willMoveToWindow:withAncestorView:]
5  UIKitCore        -[UIView(Internal) _addSubview:positioned:relativeTo:]
6  UIKitCore        ___67-[UIViewControllerBuiltinTransitionViewAnimator animateTransition:]_block_invoke_2
7  UIKitCore        +[UIView(Animation) performWithoutAnimation:]
8  UIKitCore        ___67-[UIViewControllerBuiltinTransitionViewAnimator animateTransition:]_block_invoke
9  UIKitCore        +[UIView _setupAnimationWithDuration:delay:view:options:factory:animations:start:animationStateGenerator:completion:]
10 UIKitCore        +[UIView(UIViewAnimationWithBlocks) animateWithDuration:delay:options:animations:completion:]
11 UIKitCore        -[UIViewControllerBuiltinTransitionViewAnimator animateTransition:]
12 UIKitCore        ____UIViewControllerTransitioningRunCustomTransition_block_invoke_2
13 UIKitCore        +[UIInputResponderController _pinInputViewsForInputResponderController:onBehalfOfResponder:duringBlock:]
14 UIKitCore        ____UIViewControllerTransitioningRunCustomTransition_block_invoke.663
15 UIKitCore        +[UIView(Animation) _setAlongsideAnimations:toRunByEndOfBlock:]
16 UIKitCore        __UIViewControllerTransitioningRunCustomTransition
17 UIKitCore        ___56-[UIPresentationController runTransitionForCurrentState]_block_invoke.491
18 UIKitCore        -[_UIAfterCACommitBlock run]
19 UIKitCore        __runAfterCACommitDeferredBlocks
20 UIKitCore        __cleanUpAfterCAFlushAndRunDeferredBlocks
21 UIKitCore        __afterCACommitHandler
22 CoreFoundation   ___CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
23 CoreFoundation   ___CFRunLoopDoObservers
24 CoreFoundation   ___CFRunLoopRun
25 CoreFoundation   _CFRunLoopRunSpecific
26 GraphicsServices _GSEventRunModal
27 UIKitCore        -[UIApplication _run]
28 UIKitCore        _UIApplicationMain

Screenshots

This is the "breadcrumb" from Bugsnag: Screenshot 2021-05-19 at 01 12 07

Package versions

WoLewicki commented 3 years ago

Can you provide a snack/snippet with minimal configuration needed to reproduce the issue? I am afraid we cannot do anything without it since the logs are not descriptive.

mczernek commented 3 years ago

I am also having this issue. In my case it is Modal within stackNavigator being dismissed. Workaround for me was postpone dismissing to next JS Thread tick with setTimeout(() => setVisible(false), 0)

chrisozgo99 commented 3 years ago

I am also having this issue on iOS, seemingly randomly but also quite often, due to a modal being closed. The set timeout method mentioned above did not work. It is a fatal error. My error message in XCode is Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller:<RNScreensViewController: 0x14fe43510> should have parent view controller:(null) but actual parent is:<RNSScreen: 0x14fec61f0>' terminating with uncaught exception of type NSException

chrisozgo99 commented 3 years ago

Temporary workaround has seemed to be using the react-native-modal package as the same problems do not arise and it offers the same functionality as React Native core Modal component. Doesn't fix the problem at hand though

WoLewicki commented 3 years ago

@chrisozgo99 can you provide a reproduction of the issue so we can work on it? One reason for the crash I can think of is due to the logic of react-native's Modal implementation. It makes some assumptions about the ViewControllers hierarchy, which are invalid in the context of react-native-screens since we use ViewControllers too. I think it is safer to use stackPresentation: 'modal' included in native-stack navigator or mimic the native modal using mode: 'modal' from basic stack navigator. Still a reproduction of the crash would be very helpful.

rcase100 commented 3 years ago

I am also having this issue on iOS, the app crashes when I set "Dashboard" as the initialRoute, but works find with "Menu" as the initialRoute. Using enableScreens(false) does solve the issue, but sounds like that's not an ideal workaround. RN 0.64.2, react 17.0.1, react-native-screens 3.4.0, react-navigation 4.4.4, XCode 12.4. App.js, in render():

...
            let tabNavs = {};

            //the home screen for each tab goes here (in tabNavs)

                tabNavs['Dashboard'] = {
                    screen: (props) => <DashboardMain {...props}/>,
                    navigationOptions: {
                        title: "Dash",
                        tabBarIcon: ({focused, horizontal, tintColor}) => {
                            if (focused) {
                                return <Icons.IconDashboardNewFill/>
                            } else {
                                return <Icons.IconDashboardNewOutline/>
                            }
                        }
                    }
                };

            tabNavs['Menu'] = {
                screen: (props) => <MenuMain {...props} onChangeOrg={cRef.changeOrg} onLogout={cRef.logout}/>,
                navigationOptions: {
                    title: "More",
                    tabBarIcon: ({focused, horizontal, tintColor}) => {
                        if (focused) {
                            return <Icons.IconMore fillOpacity="1" fill={AppStyler.color("blue")}/>
                        } else {
                            return <Icons.IconMoreOutline/>
                        }
                    }
                }
            };

            let BottomTabNavigator = createBottomTabNavigator(tabNavs,
                {
                    tabBarComponent: props =>
                        <BottomTabNav {...props} />,
                    initialRouteName: "Dashboard"
                }
            );

            let navs = {};

            //all screens that shouldn't show the bottom tab bar go here (in navs)

            navs['Tabs'] = {
                screen: BottomTabNavigator,
                navigationOptions: {
                    headerShown: false  //hides header for just this screen/stack
                },
            };

            navs['CompanySelectorPage'] = {
                screen: () => {
                    this.setState({phase: App.PHASE_CMPSEL});
                    return null;
                },
                //navigationOptions: {title: () => null}
            };
...
            let RootStack = createStackNavigator(navs);

            const AppContainer = createAppContainer(RootStack);
            return <AppContainer />
...
WoLewicki commented 3 years ago

@rcase100 can you provide an example in a form of a repo so we can work on it? It is hard to get any information from such a snippet unfortunately.

rcase100 commented 3 years ago

I'll try to. I have some private libraries in there so will need to remove them first.

On Tue, Jul 6, 2021 at 9:46 AM Wojciech Lewicki @.***> wrote:

@rcase100 https://github.com/rcase100 can you provide an example in a form of a repo so we can work on it? It is hard to get any information from such a snippet unfortunately.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/software-mansion/react-native-screens/issues/944#issuecomment-874825086, or unsubscribe https://github.com/notifications/unsubscribe-auth/ALSRN3VUWETVMNODNGYLZQDTWMJKTANCNFSM45DPWHHQ .

WoLewicki commented 3 years ago

I am closing it due to no response in more than 30 days. Please provide a reproduction and then we can reopen it.

pt7892 commented 3 years ago

Here is video of this issue:

https://user-images.githubusercontent.com/20343932/141505520-7345a02a-4238-4a95-90a3-1b893d0ecc1c.mp4

Here is repo for reproduction of this issue:

https://github.com/pt7892/UIViewControllerHierarchyInconsistency-repro

Steps to reproduce:

  1. Start app
  2. Press CrashStack navigation link in bottom navigation tab bar
  3. If issue does not appear, reload metro bundler and try again

Issue is not consistent, but trying couple of times steps from above should trigger this bug

Crash log:

2021-11-12 17:50:09.149613+0100 AwesomeTSProject[62797:5010933] [Presentation] Presenting view controller <RCTModalHostViewController: 0x7f7bdbf40d10> from detached view controller <RNSScreen: 0x7f7bdcb39bb0> is discouraged.

2021-11-12 17:50:09.663118+0100 AwesomeTSProject[62797:5010933] *** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller:<RNScreensViewController: 0x7f7bdcb29500> should have parent view controller:(null) but actual parent is:<RNSScreen: 0x7f7bdcb29eb0>'

@WoLewicki can we reopen this?

hussainsherwani commented 3 years ago

@pt7892 +1 also getting the same issue, issue is not consistent but coming

WoLewicki commented 3 years ago

I debugged it and it seems like there is a race condition between Modal and Screen view controllers being attached/detached. I am not sure if we can do anything about it since it comes from asynchronous behaviors of these events. The solution to this is probably adding setTimeout for showing the modal in the new screen, so first the proper native hierarchy of view controllers is established, something like this:

const CrashScreen: FC = () => {
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    setTimeout(() => {
      setShowModal(true);
    }, 0);
  }, []);

  return (
    <View style={styles.container}>
      <Text>Crash screen</Text>
      <Modal visible={showModal}>
        <View style={styles.container}>
          <Text>Loading</Text>
        </View>
      </Modal>
    </View>
  );
};

Can you check if it resolves the issue?

pt7892 commented 2 years ago

Yes, this those resolve the issue, but i guess this is not optimal solution as this could lead to situations where you can see layout, which should be hidden, for a glitch of a second before Modal pops out, plus every time you use Modal you would need to check if this issue could happen and implement this fix.

Isn't there anything that can be done to fix this in different way?

WoLewicki commented 2 years ago

I think the easiest solution is using either native-stack with e.g. stackPresentation: 'fullScreenModal' or modal style of presentation in stack navigator. It would resolve the problems of race conditions between react-native-screens and VCs from react-native's Modal.

jacquesdev commented 2 years ago

Temporary workaround has seemed to be using the react-native-modal package as the same problems do not arise and it offers the same functionality as React Native core Modal component. Doesn't fix the problem at hand though

@chrisozgo99 - that library extends react-native modal, so curious why it would fix the issue? Do you have any ideas?

SethArchambault commented 2 years ago

Getting this same issue.. Can we reopen?

WoLewicki commented 2 years ago

@SethArchambault doesn't this solve the issue: https://github.com/software-mansion/react-native-screens/issues/944#issuecomment-971559549 ?

SethArchambault commented 2 years ago

@WoLewicki I'll try it - so does this mean anytime we set the visibility of a modal we need to do it in a setTimeout? Feels like a bit of a hack right?

WoLewicki commented 2 years ago

I think it is only needed if you open a screen with the modal shown from the beginning since then react-native-screens also changes the native controller hierarchy.

SethArchambault commented 2 years ago

Ahha got it, thanks!

arron-olio commented 2 years ago

@WoLewicki we are opening multiple modals at the same time and our app crashes on iOS, do you have any recommendations for this scenario?

WoLewicki commented 2 years ago

@arron-olio do you mean Modal component from react-native? If so, maybe you should try using presentation: 'modal' from native-stack instead since I am not sure if multiple modals scenario is handled by react-native code.

arron-olio commented 2 years ago

@WoLewicki Thank you for your response, yes we are currently just using the Modal from react-native. We currently have a few stacks, all of which are using the react-navigation stack. If we want to switch from react-native Modal to using a stack with screens using presentation: 'modal', does it make sense to switch all of our stacks to use native-stack or would it still work to just use native-stack for this one stack?

WoLewicki commented 2 years ago

I think you can switch only this one stack, but since native-stack is the recommended one and is the most performant one, it would be good for your app as long as you don't have some very specific options that cannot be handled by native-stack.

wood1986 commented 1 year ago

Hey, I think this issue is likely on the react-native library itself. When I patch it with this code, it will not crash any more.

https://github.com/wood1986/react-native-modal-crash/blob/master/.yarn/patches/react-native-npm-0.70.6-94c39d80fa.patch

This will solve what @WoLewicki mentioned is the race condition. I will create a PR on the react-native and seek for their opinion

Here is my repo https://github.com/wood1986/react-native-modal-crash. Its implementation is based on @pt7892 but I use the latest dependencies for @react-navigation/*, react-native-safe-area-context, react-native-screens and react-native

If you revert my last commit https://github.com/wood1986/react-native-modal-crash/commit/86e7bc1adf444c1645c0d6078b0d6d427cdf6a36 (after revert or hard reset, you need to rerun git clean -xfdq and yarn install), It always crashes on iOS

wood1986 commented 1 year ago

Hey guys, react-native took my patch. Can you guys try again?

tomekzaw commented 1 year ago

cc @kkafar @WoLewicki

WoLewicki commented 1 year ago

I think we should ask people who reported on this issue if applying the fix from @wood1986 fixes their crashes, cc @yberstad @chrisozgo99 @rcase100 @pt7892 @hussainsherwani @SethArchambault @arron-olio.

SethArchambault commented 1 year ago

Great! What version of react-native is this in?

wood1986 commented 1 year ago

It is not in any release yet. They plan to include it in 0.70.1

SethArchambault commented 1 year ago

🙏

numandev1 commented 1 year ago

getting this error only when I enable the fabric name __NSCFConstantString * "UIViewControllerHierarchyInconsistency" 0x000000020be3fdf0

Exception NSException * "A view can only be associated with at most one view controller at a time! View <RNSScreenView: 0x113814000; frame = (0 0; 0 0); layer = <CALayer: 0x2812ead00>> is associated with <RNSScreen: 0x111e15f20>. Clear this association before associating this view with <RNSScreen: 0x11d6873f0>." 0x0000000281d4e4f0

here is my code

const TestComponent = () => {
  return <Text>TestComponent</Text>;
};
const App = () => {
  return (
    <NavigationContainer>
      <RootStack.Navigator
        screenOptions={{
          headerHideBackButton: true,
        }}
      >
        <RootStack.Screen
          name="Chapter"
          options={{
            title: "Fabric Example",
            headerShown: false,
          }}
          initialParams={{
            index: 0,
            chapterRoute: "Chapter",
            afterChapterRoute: "HeaderDemo",
          }}
          component={TestComponent}
        />
        <RootStack.Screen
          name="HeaderDemo"
          component={TestComponent}
          options={{ title: "Header Demo" }}
        />
      </RootStack.Navigator>
    </NavigationContainer>
  );
};

export default App;
    "react-native": "0.72.1",
    "react-native-screens": "3.22.0",
image
Sowed commented 1 year ago

Getting this too with Fabric

"react-native": "0.72.3",
"react-native-screens": "3.22.0",
*** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'A view can only be associated with at most one view controller at a time! View <RNSScreenView: 0x1413df600; frame = (0 0; 0 0); layer = <CALayer: 0x60000007b400>> is associated with <RNSScreen: 0x140c95720>. Clear this association before associating this view with <RNSScreen: 0x140c95b00>.'
*** First throw call stack:
numandev1 commented 1 year ago

Getting this too with Fabric

"react-native": "0.72.3",
"react-native-screens": "3.22.0",
*** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'A view can only be associated with at most one view controller at a time! View <RNSScreenView: 0x1413df600; frame = (0 0; 0 0); layer = <CALayer: 0x60000007b400>> is associated with <RNSScreen: 0x140c95720>. Clear this association before associating this view with <RNSScreen: 0x140c95b00>.'
*** First throw call stack:

@Sowed I am getting the same issue, can you share your package.json? i also created a issue for it https://github.com/software-mansion/react-native-screens/issues/1809

numandev1 commented 1 year ago

@Sowed are you using this react-native-lottie-splash-screen package? maybe splash screen is creating problem

Sowed commented 1 year ago

@Sowed are you using this react-native-lottie-splash-screen package? maybe splash screen is creating problem

No @numandev1. The app was building fine until I tested out upgrading the packages to RN 0.72.3. Here part of the the package.json. Working in a mono repo so some packages are stripped out. Left those that I suspect might be the culprit.

{
  "dependencies": {
    "@expo-google-fonts/dev": "0.2.3",
    "@expo-google-fonts/lexend-deca": "0.2.3",
    "@expo-google-fonts/noto-sans-arabic": "0.2.3",
    "@expo/metro-config": "^0.10.6",
    "@expo/webpack-config": "~18.1.1",
    "@react-native-async-storage/async-storage": "1.18.2",
    "@react-navigation/bottom-tabs": "6.5.7",
    "@react-navigation/native": "6.1.6",
    "@react-navigation/native-stack": "6.9.12",
    "@react-navigation/stack": "6.3.16",
    "@shopify/restyle": "2.4.2",
    "axios": "^1.3.6",
    "date-fns": "^2.29.2",
    "expo": "^49.0.3",
    "expo-application": "~5.3.0",
    "expo-haptics": "~12.4.0",
    "expo-linking": "~5.0.2",
    "expo-modules-core": "~1.5.7",
    "expo-permissions": "14.2.1",
    "expo-splash-screen": "~0.20.4",
    "i18n-js": "4.3.0",
    "lottie-react-native": "^6.0.0-rc.5",
    "moti": "0.25.3",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-native": "0.72.3",
    "react-native-blob-util": "0.17.3",
    "react-native-bootsplash": "4.6.0",
    "react-native-code-push": "^8.0.2",
    "react-native-codegen": "0.71.5",
    "react-native-config": "1.5.0",
    "react-native-fs": "2.20.0",
    "react-native-gesture-handler": "~2.12.0",
    "react-native-keychain": "^8.1.1",
    "react-native-mmkv": "2.8.0",
    "react-native-modal": "13.0.1",
    "react-native-modal-datetime-picker": "15.0.1",
    "react-native-reanimated": "3.3.0",
    "react-native-safe-area-context": "4.7.1",
    "react-native-screens": "3.22.0",
    "react-native-svg": "13.10.0",
    "react-native-webview": "^13.2.2"
  },
  "devDependencies": {
    "@babel/core": "7.21.4",
    "@babel/plugin-proposal-decorators": "7.21.0",
    "@babel/plugin-proposal-export-namespace-from": "7.18.9",
    "@babel/plugin-proposal-optional-catch-binding": "7.18.6",
    "@babel/preset-env": "7.21.4",
    "@babel/runtime": "7.21.0",
    "@react-native/eslint-config": "^0.72.2",
    "@react-native/metro-config": "^0.72.9",
    "@rnx-kit/metro-config": "1.3.6",
    "@rnx-kit/metro-resolver-symlinks": "0.1.28",
    "@rnx-kit/metro-serializer-esbuild": "^0.1.22",
    "@tsconfig/react-native": "^3.0.0",
    "@types/jest": "^29.2.1",
    "@types/react": "~18.2.14",
    "@types/react-native": "~0.70.6",
    "babel-jest": "29.2.1",
    "babel-loader": "8.2.5",
    "babel-plugin-root-import": "6.6.0",
    "jest": "^29.6.1",
    "jest-circus": "26",
    "jest-environment-node": "26",
    "jest-expo": "49.0.0",
    "metro-config": "0.77.0",
    "metro-react-native-babel-preset": "0.77.0",
    "metro-source-map": "0.73.9",
    "mocha": "6",
    "patch-package": "6.4.7",
    "postinstall-prepare": "1.0.1",
    "query-string": "^7.0.1",
    "react-devtools-core": "4.24.7",
    "react-native-gradle-plugin": "0.71.19",
    "react-native-web": "~0.18.7",
    "ts-jest": "^29.1.1",
    "typescript": "^5.1.3",
    "webpack-dev-server": "^3"
  }
}
timmyjose commented 10 months ago

I'm seeing a possibly related error (in iOS emulator, Release configuration only):

[CoreFoundation] *** Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'A view can only be associated with at most one view controller at a time! View <RNSScreenView:
0x1250ab000; frame = (0 0; 0 0); layer = <CALayer: 0x600002ff5d00>> is associated with <RNSScreen: 0x1242532b0>. Clear this association before associating this view with <RNSScreen: 0x124253690>.'
*** First throw call stack:
(
0   CoreFoundation                      0x0000000180437330 __exceptionPreprocess + 172
1   libobjc.A.dylib                     0x0000000180051274 objc_exception_throw + 56
2   CoreFoundation                      0x0000000180437240 -[NSException initWithCoder:] + 0
3   UIKitCore                           0x0000000117d8d638 -[UIView __setViewDelegate:] + 140
4   UIKitCore                           0x00000001172590c0 -[UIViewController setView:] + 368
5   <elided>                            0x000000010473a874 -[RNSScreen initWithView:] + 96
6   <elided>                            0x000<…>

Possibly pertinent dependencies are (can give the full package.json if that would help):

    "react-native": "0.72.7",
    "react-native-modal": "^13.0.1",
    "react-native-screens": "~3.27.0",   
    "expo-splash-screen": "~0.20.5",