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

Trunk无法识别reqwest特性,Yew项目编译报错求助

解决Trunk构建Yew应用时reqwest blocking特性找不到的问题

你遇到的核心问题是reqwest的blocking特性不支持WebAssembly(Wasm)目标:Trunk默认会为Wasm构建Yew的CSR应用,而Wasm环境下reqwest没有blocking模块;但cargo build默认针对本地native目标编译,所以能正常通过。

解决方案:改用reqwest异步客户端(Wasm环境唯一可行方案)

Yew组件的view方法是同步的,但可以通过异步副作用处理网络请求,具体步骤如下:

  1. 调整Cargo.toml依赖
    移除blocking特性,添加Wasm环境需要的异步支持依赖:
[dependencies]
reqwest = { version = "0.11.0", features = ["json", "wasm-bindgen"] }
yew = { version = "0.20.0", features = ["csr"] }
wasm-bindgen-futures = "0.4"
  1. 修改请求代码为异步实现
    在Yew组件中通过use_effect_with结合spawn_local执行异步请求:
use yew::prelude::*;
use wasm_bindgen_futures::spawn_local;
use reqwest::Client;

#[function_component(GitHubDirListing)]
pub fn github_dir_listing() -> Html {
    let repo_items = use_state(|| Vec::new());
    let repo_items_clone = repo_items.clone();

    // 组件挂载后执行异步请求
    use_effect_with((), move |_| {
        spawn_local(async move {
            let client = Client::new();
            let contents_url = "https://api.github.com/repos/你的用户名/你的仓库名/contents";
            
            match client.get(contents_url).send().await {
                Ok(response) => {
                    if let Ok(data) = response.json::<Vec<serde_json::Value>>().await {
                        repo_items_clone.set(data);
                    }
                }
                Err(e) => {
                    web_sys::console::log_1(&format!("请求失败: {}", e).into());
                }
            }
        });
        || () // 清理函数(此处无需操作)
    });

    html! {
        <div>
            {for repo_items.iter().map(|item| html! { <p>{item["name"].as_str().unwrap_or("未知")}</p> })}
        </div>
    }
}

可选:同时支持native和Wasm目标

如果需要本地调试时用blocking客户端,Wasm用异步客户端,可以在Cargo.toml中配置目标依赖:

[dependencies]
reqwest = { version = "0.11.0", features = ["json"] }
yew = { version = "0.20.0", features = ["csr"] }
wasm-bindgen-futures = "0.4"

# 仅在非Wasm目标启用blocking特性
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.reqwest]
features = ["blocking"]

你之前尝试的--features参数无法解决问题,因为Wasm目标下reqwest的blocking特性本身就不被支持,必须改用异步方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:15:12