python runtime_error ai_generated true

RuntimeError: 没有正在运行的事件循环

RuntimeError: no running event loop

ID: python/fastapi-background-task-event-loop

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2025-01-08首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

在没有运行事件循环的同步后台任务或线程中调用了 asyncio.get_event_loop() 或 loop.run_until_complete()。

English

asyncio.get_event_loop() or loop.run_until_complete() is called inside a sync background task or thread where no loop is running.

generic

解决方案

  1. 90% 成功率
    Make the background task async:
    async def task(): await do_work()
    background_tasks.add_task(task)
  2. 82% 成功率
    In a thread, use asyncio.run(coro()) for self-contained work.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Creates leaks and doesn't share the server loop; resources bound to another loop fail.

  2. 80% 失败

    Blocks the loop and doesn't address the missing loop in the thread.