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

如何显式使用pytransitions Asyncio扩展的AsyncState类?报错排查

问题原因分析

一、StartState:on_enter()未自动触发的原因

pytransitions的AsyncState不会自动将类内定义的on_enter方法注册为进入回调——这和GoF状态模式的直觉逻辑有差异。默认情况下,你必须显式告知AsyncMachine绑定这些回调,常见的正确做法有三种:

  1. 创建AsyncState实例时直接指定回调
  2. 通过机器的add_state方法配置回调参数
  3. 使用装饰器标记回调方法

示例代码:

from transitions.extensions.asyncio import AsyncMachine, AsyncState

class StartState(AsyncState):
    async def on_enter(self):
        print("Entered StartState")

# 方式1:创建状态时指定回调
start_state = StartState(on_enter="on_enter")

# 方式2:通过add_state配置回调
machine = AsyncMachine(states=[], initial=None)
machine.add_state(StartState(), on_enter="on_enter")

如果没做这类显式配置,机器根本不会识别你定义的on_enter方法,自然不会触发。

二、手动添加回调时出现'list' object is not callable的原因

这个错误几乎都是因为你重复给回调属性赋值,导致它从单个可调用对象变成了列表,后续机器尝试调用该回调时,会误把列表当成函数执行,从而抛出类型错误。

比如你可能写了类似这样的错误代码:

# 错误示例:先赋值单个函数,又追加成列表
start_state = StartState()
start_state.on_enter = start_state.on_enter
start_state.on_enter.append(some_other_func)
# 此时start_state.on_enter是列表,机器调用时就会报错

正确的手动添加回调方式:

# 方式1:创建状态时直接传入回调列表
start_state = StartState(on_enter=[start_state.on_enter, some_other_func])

# 方式2:用机器的add_callback方法绑定
machine.add_callback("enter_start_state", start_state.on_enter)

另外要注意,pytransitions的回调系统中,若传字符串作为回调参数,会从状态实例或机器关联的模型对象中查找对应方法;若传可调用对象,要确保是单个函数或函数列表,不要中途把变量类型从函数改成列表后再被当作函数调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:20:00