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

调用.manage()后Tauri状态仍未被管理的问题求助

调用.manage()后Tauri状态仍未被管理的问题求助

我现在在写一个基础的Tauri应用,尝试管理应用状态。项目能正常编译,但从前端调用命令时,总会遇到这样的运行时错误:

state is not managed for field state on command test_cmd. You must call .manage() before using this command

我是这样构建Tauri应用的,你能看到我确实调用了.manage()方法:

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let db_state = Arc::new(Mutex::new(DatabaseState::new()));

    println!("db_state initialized ");

    tauri::Builder::default()
        .setup(|app| {
            #[cfg(debug_assertions)]
            app.get_webview_window("main").unwrap().open_devtools();
            Ok(())
        })
        .plugin(tauri_plugin_shell::init())
        .manage(db_state)
        .invoke_handler(tauri::generate_handler![test_cmd])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

这是我用于复现问题的简化命令:

#[tauri::command]
pub async fn test_cmd(state: State<'_, Arc<Mutex<DatabaseState>>>) -> Result<String, String> {
    Ok("test_cmd executed".into())
}

我的DatabaseState结构体定义如下:

pub struct DatabaseState {
    service: Option<BoxedDatabaseService>,
}

impl DatabaseState {
    pub fn new() -> Self {
        DatabaseState { service: None }
    }

    pub fn set_service(&mut self, db_service: BoxedDatabaseService) {
        self.service = Some(db_service);
    }

    pub fn get_service(&self) -> Option<&BoxedDatabaseService> {
        self.service.as_ref()
    }

}

另外,所有不依赖状态的命令都能正常工作,只有涉及状态的命令会报这个错。

有没有大佬知道该怎么解决这个问题,或者我需要检查哪些地方?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.15 09:48:05