python runtime_error ai_generated true

运行时错误:异步生成器引发了 StopAsyncIteration

RuntimeError: async generator raised StopAsyncIteration

ID: python/starlette-async-iterator-exhausted

其他格式: JSON · Markdown 中文 · English
80%修复率
81%置信度
0证据数
2024-09-14首次发现

版本兼容性

版本状态引入弃用备注
3.10 active
3.11 active

根因分析

Starlette 的异步生成器在迭代过程中被提前关闭或耗尽

English

Starlette 的异步生成器在迭代过程中被提前关闭或耗尽

generic

解决方案

  1. 90% 成功率 确保异步生成器正确使用 async for 循环
    async for item in async_generator():
        process(item)
  2. 85% 成功率 在调用处捕获 StopAsyncIteration
    try:
        async for item in gen:
            ...
    except StopAsyncIteration:
        pass

无效尝试

常见但无效的做法:

  1. 在生成器函数中添加 try-except 捕获 StopAsyncIteration 80% 失败

    生成器内部不应捕获此异常,会导致状态混乱

  2. 使用同步生成器替代 70% 失败

    破坏了异步上下文,可能阻塞事件循环