You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Decompose与Koin时遇DefaultChildStack重复注册异常求助

解决Decompose + Koin中"Another supplier is already registered with the key: DefaultChildStack"异常

问题原因

你将childStack定义为动态计算的getter属性,每次访问该属性都会调用childStack()函数创建全新的ChildStack实例。每个ChildStack内部会向Decompose的StateKeeper注册名为DefaultChildStack的状态保存器,重复注册同一个key就会触发这个IllegalStateException。

解决方案

将childStack改为仅初始化一次的属性,确保整个组件生命周期内只创建一个ChildStack实例,避免重复注册状态key。

修改DefaultRootComponent代码

把原来的getter属性改成lazy初始化的val:

class DefaultRootComponent(componentContext: ComponentContext) : RootComponent,
    ComponentContext by componentContext, KoinComponent {

    ...

    override val childStack: Value<ChildStack<*, RootComponent.Child>> by lazy {
        childStack(
            source = navigation,
            initialConfiguration = Config.HomeScreen,
            handleBackButton = true,
            childFactory = ::createChild
        )
    }
    ...
}

或者直接在初始化阶段创建实例:

class DefaultRootComponent(componentContext: ComponentContext) : RootComponent,
    ComponentContext by componentContext, KoinComponent {

    ...

    private val _childStack = childStack(
        source = navigation,
        initialConfiguration = Config.HomeScreen,
        handleBackButton = true,
        childFactory = ::createChild
    )
    
    override val childStack: Value<ChildStack<*, RootComponent.Child>>
        get() = _childStack
    ...
}

验证效果

修改后,组件在进程死亡或屏幕旋转时:

  • childStack只会实例化一次,不会重复注册状态key
  • Decompose会正常保存/恢复ChildStack的状态,组件实例和状态得以保留

内容的提问来源于stack exchange,提问作者ayitinya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 06:23:13