async def _as_state_update(
        self,
        handler: EventHandler,
        events: EventSpec | list[EventSpec] | None,
        final: bool,
    ) -> StateUpdate:
        """Convert the events to a StateUpdate.

        Fixes the events and checks for validity before converting.

        Args:
            handler: The handler where the events originated from.
            events: The events to queue with the update.
            final: Whether the handler is done processing.

        Returns:
            The valid StateUpdate containing the events and final flag.
        """
        # get the delta from the root of the state tree
        state = self._get_root_state()

        token = self.router.session.client_token

        # Convert valid EventHandler and EventSpec into Event
        fixed_events = fix_events(self._check_valid(handler, events), token)

        try:
            # Get the delta after processing the event.
            delta = await state._get_resolved_delta()
            state._clean()

            return StateUpdate(
                delta=delta,
                events=fixed_events,
                final=final if not handler.is_background else True,
            )
        except Exception as ex:
            state._clean()

            event_specs = (
                prerequisites.get_and_validate_app().app.backend_exception_handler(ex)
            )

            if event_specs is None:
                return StateUpdate()

            event_specs_correct_type = cast(
                list[EventSpec | EventHandler] | None,
                [event_specs] if isinstance(event_specs, EventSpec) else event_specs,
            )
            fixed_events = fix_events(
                event_specs_correct_type,
                token,
                router_data=state.router_data,
            )
            return StateUpdate(
                events=fixed_events,
                final=True,
            )
Convert the events to a StateUpdate.

        Fixes the events and checks for validity before converting.

        Args:
            handler: The handler where the events originated from.
            events: The events to queue with the update.
            final: Whether the handler is done processing.

        Returns:
            The valid StateUpdate containing the events and final flag.
        
reflex/state.py