python
runtime_error
ai_generated
true
RuntimeError: Cannot add middleware after an application has started
ID: python/starlette-staticfiles-mount-order
80%Fix Rate
85%Confidence
0Evidence
2024-06-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.100+ | active | — | — | — |
| 0.110+ | active | — | — | — |
Root Cause
app.add_middleware / mount called inside a route handler or after the ASGI app has begun serving requests.
generic中文
在路由处理程序内部或 ASGI 应用开始处理请求之后调用了 app.add_middleware / mount。
Workarounds
-
95% success
Move app.add_middleware(...) and app.mount(...) to module top-level before uvicorn.run(app).
-
80% success
If dynamic, build a fresh Starlette app per config and swap it in the ASGI server.
Dead Ends
Common approaches that don't work:
-
70% fail
Timing issue is runtime, not import order.
-
80% fail
Middleware silently not applied; behavior unchanged.