python runtime_error ai_generated true

RuntimeError: 任务获取了附加到不同事件循环的 Future

RuntimeError: Task got Future attached to a different loop

ID: python/asyncio-task-got-future-different-loop

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

版本兼容性

版本状态引入弃用备注
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

根因分析

在某个事件循环下创建的协程或 Future 被另一个循环 await,例如两次调用 asyncio.run() 或混用 loop.run_until_complete() 与 asyncio.run()。

English

A coroutine or Future created under one event loop was awaited on another loop, e.g. by calling asyncio.run() twice or mixing loop.run_until_complete() with asyncio.run().

generic

解决方案

  1. 95% 成功率
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())  # single entry point
  2. 90% 成功率
    # In Jupyter/IPython or uvicorn, just 'await main()'
    # Do NOT call asyncio.run() inside an already-running loop

无效尝试

常见但无效的做法:

  1. 85% 失败

    The Future object still references the original loop; identity mismatch remains.

  2. 80% 失败

    ensure_future still binds to the current loop, not the Future's original loop.