improve error message for ComponentState mixins

This commit is contained in:
Benedikt Bartscher 2024-11-10 21:15:59 +01:00
parent b3fb1bdca0
commit a91f89aade
No known key found for this signature in database

View File

@ -86,6 +86,7 @@ from reflex.utils.exceptions import (
ImmutableStateError, ImmutableStateError,
InvalidStateManagerMode, InvalidStateManagerMode,
LockExpiredError, LockExpiredError,
ReflexRuntimeError,
SetUndefinedStateVarError, SetUndefinedStateVarError,
StateSchemaMismatchError, StateSchemaMismatchError,
) )
@ -2365,6 +2366,23 @@ class ComponentState(State, mixin=True):
# The number of components created from this class. # The number of components created from this class.
_per_component_state_instance_count: ClassVar[int] = 0 _per_component_state_instance_count: ClassVar[int] = 0
def __init__(self, *args, **kwargs):
"""Do not allow direct initialization of the ComponentState.
Args:
*args: The args to pass to the State init method.
**kwargs: The kwargs to pass to the State init method.
Raises:
ReflexRuntimeError: If the ComponentState is initialized directly.
"""
if type(self)._mixin:
raise ReflexRuntimeError(
f"{ComponentState.__name__} {type(self).__name__} is not meant to be initialized directly. "
+ "Use the `create` method to create a new instance and access the statte via the `State` attribute."
)
super().__init__(*args, **kwargs)
@classmethod @classmethod
def __init_subclass__(cls, mixin: bool = True, **kwargs): def __init_subclass__(cls, mixin: bool = True, **kwargs):
"""Overwrite mixin default to True. """Overwrite mixin default to True.