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

为何Tauri调用函数时会修改参数名称(下划线转驼峰)?

问题:Tauri命令参数名蛇形转驼峰导致调用失败?

我正在使用Tauri构建GUI应用。后端Rust代码中定义了两个命令:

#[tauri::command]
fn functional_test(msg: String) {
    println!("Received : {}", msg);
}

#[tauri::command]
fn no_functional_test(my_msg: String) {
    println!("Received : {}", my_msg);
}

fn main() {
    tauri::Builder::default()
        .setup(...)
        .invoke_handler(tauri::generate_handler![functional_test, no_functional_test])
        .run(tauri::generate_context!())
        .expect("failed to run app");
}

注意这两个函数仅参数名称不同:msg 和 my_msg。

前端(React)代码如下:

export function AComponent({name}: {name: string}) {
    useEffect(() => {
        const fetchSomething = async () => {
            try {
                await invoke('functional_test', {msg:"This is a message"})
                await invoke('no_functional_test', {my_msg:"This is also a message"})
            } catch (error) {
                await invoke('functional_test', {msg:error})
            }
        };

        fetchSomething();
    }, [name]);

    return (...)
}

运行输出如下:

Received : This is a message
Received : invalid args `myMsg` for command `no_functional_test`: command no_functional_test missing required key myMsg

可见Tauri期望参数名为myMsg,而非后端定义的my_msg。请问这是什么原因?是否属于正常现象?


这是Tauri的默认行为,属于正常现象。

Tauri内部会自动将Rust代码里的蛇形命名(snake_case,比如my_msg)转换为JavaScript/TypeScript常用的驼峰命名(camelCase,比如myMsg),目的是契合前后端不同的社区命名规范:

  • Rust社区惯用蛇形命名
  • JS/TS社区惯用驼峰命名

所以当你在后端定义参数my_msg时,Tauri会自动将其映射为前端调用时的myMsg参数名。

解决方法

有两种方式处理这个问题:

  1. 前端适配:调用命令时使用驼峰参数名,把{my_msg:"This is also a message"}改成{myMsg:"This is also a message"}
  2. 后端禁用自动转换:如果想保持参数名一致,可以给#[tauri::command]宏添加rename_all = "none"属性,关闭命名转换:
#[tauri::command(rename_all = "none")]
fn no_functional_test(my_msg: String) {
    println!("Received : {}", my_msg);
}

这样前端就可以直接用my_msg作为参数名调用了。

内容的提问来源于stack exchange,提问作者Fabien Denoyelle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:00:23