# AttributeError: 'State' object has no attribute 'db'

- **ID:** `python/starlette-state-access-error`
- **Domain:** python
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

尝试访问Starlette应用state对象中未设置的属性，例如数据库连接。

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **在应用启动事件中初始化state属性** (95% success)
   ```
   from starlette.applications import Starlette; app = Starlette(); @app.on_event('startup') async def startup(): app.state.db = await create_db_connection()
   ```
2. **在访问前检查属性是否存在** (90% success)
   ```
   if hasattr(app.state, 'db'): await app.state.db.execute(query)
   ```

## Dead Ends

- **在路由中直接使用app.state.db而未初始化** — state对象为空。 (90% fail)
- **使用全局变量存储数据库连接** — 可能导致连接泄露。 (70% fail)
