@@ -2463,16 +2463,30 @@ class OnLoadInternalState(State):
24632463 This is a separate substate to avoid deserializing the entire state tree for every page navigation.
24642464 """
24652465
2466+ # Cannot properly annotate this as `App` due to circular import issues.
2467+ _app_ref : ClassVar [Any ] = None
2468+
24662469 def on_load_internal (self ) -> list [Event | EventSpec | event .EventCallback ] | None :
24672470 """Queue on_load handlers for the current page.
24682471
24692472 Returns:
24702473 The list of events to queue for on load handling.
2474+
2475+ Raises:
2476+ TypeError: If the app reference is not of type App.
24712477 """
2472- # Do not app._compile()! It should be already compiled by now.
2473- load_events = prerequisites .get_and_validate_app ().app .get_load_events (
2474- self .router ._page .path
2475- )
2478+ from reflex .app import App
2479+
2480+ app = type (self )._app_ref or prerequisites .get_and_validate_app ().app
2481+ if not isinstance (app , App ):
2482+ msg = (
2483+ f"Expected app to be of type { App .__name__ } , got { type (app ).__name__ } ."
2484+ )
2485+ raise TypeError (msg )
2486+ # Cache the app reference for subsequent calls.
2487+ if type (self )._app_ref is None :
2488+ type(self )._app_ref = app
2489+ load_events = app .get_load_events (self .router ._page .path )
24762490 if not load_events :
24772491 self .is_hydrated = True
24782492 return None # Fast path for navigation with no on_load events defined.
@@ -2646,6 +2660,9 @@ def reload_state_module(
26462660 state: Recursive argument for the state class to reload.
26472661
26482662 """
2663+ # Reset the _app_ref of OnLoadInternalState to avoid stale references.
2664+ if state is OnLoadInternalState :
2665+ state ._app_ref = None
26492666 # Clean out all potentially dirty states of reloaded modules.
26502667 for pd_state in tuple (state ._potentially_dirty_states ):
26512668 with contextlib .suppress (ValueError ):
0 commit comments