python
runtime_error
ai_generated
true
RuntimeError: 应用启动后无法添加中间件
RuntimeError: Cannot add middleware after an application has started
ID: python/starlette-staticfiles-mount-order
80%修复率
85%置信度
0证据数
2024-06-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.100+ | active | — | — | — |
| 0.110+ | active | — | — | — |
根因分析
在路由处理程序内部或 ASGI 应用开始处理请求之后调用了 app.add_middleware / mount。
English
app.add_middleware / mount called inside a route handler or after the ASGI app has begun serving requests.
解决方案
-
95% 成功率
Move app.add_middleware(...) and app.mount(...) to module top-level before uvicorn.run(app).
-
80% 成功率
If dynamic, build a fresh Starlette app per config and swap it in the ASGI server.
无效尝试
常见但无效的做法:
-
70% 失败
Timing issue is runtime, not import order.
-
80% 失败
Middleware silently not applied; behavior unchanged.