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

Rust项目遇Cannot find value `css` in this scope [E0425]错误求解决

解决Rust Actix-Web中Cannot find value 'css' in this scope错误

问题原因

你遇到的错误核心是作用域捕获问题:

  1. 原代码中css函数定义在main函数内部,而HttpServer::new接收的是move闭包——Rust不允许在move闭包中捕获局部定义的函数项,因为局部函数的作用域被限制在main内部,闭包无法正确捕获它。
  2. 即使你尝试将css移出main,如果没有匹配正确的条件编译规则或缺少必要的类型导入,也会导致作用域识别失败。

解决方案

将css服务函数移到main函数外部,并且和main函数共享同一个#[cfg(feature = "ssr")]条件编译块,确保函数处于正确的作用域内,同时明确依赖类型的路径:

修改后的代码示例

use cfg_if::cfg_if;

use api::ws;
pub mod api;
pub mod model;

#[cfg(feature = "ssr")]
#[get("/style.css")] 
async fn css() -> impl actix_web::Responder {
    actix_files::NamedFile::open_async("./style/output.css").await
}

#[cfg(feature = "ssr")]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "debug");
    env_logger::init();

    use actix_files::Files;
    use actix_web::*;
    use leptos::*;
    use leptos_actix::{generate_route_list, LeptosRoutes};
    use rusty_llama::app::*;

    let conf = get_configuration(None).await.unwrap();
    let addr = conf.leptos_options.site_addr;

    let routes = generate_route_list(|| view! { <App/> });

    let model = web::Data::new(get_language_model());
    HttpServer::new(move || {
        let leptos_options = &conf.leptos_options;
        let site_root = &leptos_options.site_root;

        App::new()
            .app_data(model.clone())
            .service(css)  // 现在可以正常识别css函数
            .route("/ws", web::get().to(ws))
            .route("/api/{tail:.*}", leptos_actix::handle_server_fns())
            .leptos_routes(
                leptos_options.to_owned(),
                routes.to_owned(),
                || view! { <App/> },
            )
            .service(Files::new("/", site_root))
    })
    .bind(&addr)?
    .run()
    .await
}

关键修改点

  1. 作用域调整:把css函数移到main外部,确保它处于全局作用域(相对于main),move闭包可以直接引用静态的函数项,无需捕获。
  2. 条件编译对齐:给css函数加上#[cfg(feature = "ssr")],和main保持一致,避免特性未开启时的编译错误。
  3. 明确类型路径:使用actix_web::Responder而非依赖局部导入,避免作用域内导入缺失导致的类型识别问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:18:34