python
config_error
ai_generated
true
AssertionError: 应用启动后无法添加中间件
AssertionError: Cannot add middleware after an application has started
ID: python/starlette-middleware-order-response-headers
80%修复率
84%置信度
0证据数
2024-08-27首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.30+ | active | — | — | — |
根因分析
在 ASGI 应用已经开始提供服务后调用了 app.add_middleware()(例如在路由内或 TestClient 实例化之后)。
English
app.add_middleware() was called after the ASGI app had already started serving (e.g., inside a route or after TestClient instantiation).
解决方案
-
95% 成功率
app = FastAPI() app.add_middleware(CORSMiddleware, allow_origins=['*']) # then define routes
-
90% 成功率
def create_app(): app = FastAPI() app.add_middleware(...) return app
无效尝试
常见但无效的做法:
-
85% 失败
The middleware is never added; headers/logging silently missing.
-
90% 失败
Startup fires after the middleware stack is built; assertion still raised.