python runtime_error ai_generated true

RuntimeError: 无法从正在运行的事件循环中调用 asyncio.run()

RuntimeError: asyncio.run() cannot be called from a running event loop

ID: python/starlette-loop-already-running

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

版本兼容性

版本状态引入弃用备注
0.27+ active — — —

根因分析

同步的 FastAPI/Starlette 路由或依赖项在服务器事件循环已运行时调用了 asyncio.run()。

English

A synchronous FastAPI/Starlette route or dependency called asyncio.run() while the server's event loop was already running.

generic

解决方案

  1. 95% 成功率
    @app.get('/x')
    async def handler():
        return await some_coroutine()
  2. 75% 成功率
    import anyio
    result = anyio.from_thread.run(some_coroutine)

无效尝试

常见但无效的做法:

  1. 70% 失败

    Patches the loop but breaks uvicorn's task scheduling and can deadlock under load.

  2. 85% 失败

    Raises 'This event loop is already running' since the loop cannot be re-entered.