python runtime_error ai_generated true

RuntimeError: 应用启动后无法再添加中间件

RuntimeError: Cannot add middleware after an application has started

ID: python/starlette-middleware-order-500

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

版本兼容性

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

根因分析

在 ASGI 应用开始处理请求后(例如在 startup 事件或路由中)调用了 add_middleware。

English

add_middleware is called after the ASGI app has begun handling requests, e.g. inside a startup event or a route.

generic

解决方案

  1. 93% 成功率
    Register middleware at module level before the app starts:
    app.add_middleware(GZipMiddleware)
  2. 85% 成功率
    Use lifespan for startup logic, not middleware registration.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Startup runs after the middleware stack is built; the error is raised.

  2. 75% 失败

    The middleware is never applied, so behavior silently differs.