You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Axum使用with_state传递应用状态时出现MethodRouter类型不匹配错误的解决求助

Axum使用with_state传递应用状态时出现MethodRouter类型不匹配错误的解决求助

我正在开发一个Axum项目,使用with_state API时遇到了问题。我的目标是给Axum路由中的处理器传递应用状态(AppState),但一直收到下面的错误:

note: expected struct MethodRouter<()>
found struct MethodRouter<AppState>

下面是我的项目结构:

main.rs

#[tokio::main]
async fn main() {
    if let Ok(db) = init_db().await {
        let state = state::app_state::AppState::new(db);
        let routes = routes::root::routes();
        let router = Router::new().with_state(state).nest("/api", routes);
        let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
        axum::serve(listener, router).await.unwrap();
    }
}

root.rs

pub fn routes() -> Router {
    Router::new().merge(user_routes())
}

routes/user.rs

pub fn routes() -> Router {
    Router::new().route("/auth/register", post(register_user))
}

handler/user.rs

pub async fn register_user(Json(payload): Json<User>, State(state): State<AppState>) -> impl IntoResponse {
    ...
}

#[derive(Clone)]
pub struct AppState {
    db_conn: Database
}

impl AppState {
    pub fn new(db: Database) -> AppState {
        AppState {
            db_conn: db
        }
    }
}

错误提示MethodRouter<()>和MethodRouter<AppState>类型不匹配,我怀疑问题可能出在路由的设置或者root.rs中的合并方式上。有没有解决这个问题的建议?

我已经尝试过with_state和nest的不同配置组合,但错误仍然存在!希望能得到一些有用的见解!

备注:内容来源于stack exchange,提问作者Sasha Zoria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 10:13:10