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

使用Leptos Router出现上下文重复提供警告,求助排查原因

Leptos路由组件上下文重复提供警告的解决办法

你在Git main分支测试Leptos框架,按照路由示例实现后,浏览器控制台出现如下警告:

WARNING: You are providing a context of a type (leptos_reactive::memo::Memo<leptos_router::components::routes::RouterState>)that's already been provided higher in the context tree. If this is unintentional, there's a chance it will cause bugs, because the value of the context is now 'shadowed' in the lower parts of the tree.

翻译后警告内容:

警告:你提供的上下文类型(leptos_reactive::memo::Memo<leptos_router::components::routes::RouterState>)已在上下文树的更上层被提供。如果这不是有意为之,可能会导致bug,因为上下文的值现在在树的下层被“遮蔽”了。

你的路由组件代码如下:

#[component]
pub fn Playground(
  cx: Scope,
) -> impl IntoView {

  view! { cx,
      <Router> 
          <nav> 
              <A exact=true href="/">"Simple"</A> 
              <A href="demo1">"Demo 1"</A> 
              <A href="demo2">"Demo 2"</A> 
          </nav> 
          <main> 
              <Routes> 
                  <Route 
                      path="/" 
                      view=move |cx| view! { cx, <SimpleComponent/> } />
                  <Route 
                      path="demo1" 
                      view=move |cx| view! { cx, <Demo1 /> } />
                  <Route 
                      path="demo2" 
                      view=move |cx| view! { cx, <Demo2 /> } />
              </Routes>
          </main>
      </Router>
  }
}

问题原因

这个警告的核心是:你的Playground组件本身被嵌套在另一个<Router>组件内部。Leptos的<Router>组件会向上下文注入RouterState,如果在已经存在Router的上下文环境里再渲染一个<Router>,就会重复注入相同类型的上下文,触发该警告。

解决方法

  1. 检查应用入口代码(比如main.rs或根组件),确认是否已经渲染了一个<Router>,而Playground作为它的子组件被调用。
  2. 如果是上述情况,直接移除Playground组件里的<Router>标签,保留内部的导航、路由匹配逻辑即可。

修改后的示例代码:

#[component]
pub fn Playground(
  cx: Scope,
) -> impl IntoView {

  view! { cx,
      <nav> 
          <A exact=true href="/">"Simple"</A> 
          <A href="demo1">"Demo 1"</A> 
          <A href="demo2">"Demo 2"</A> 
      </nav> 
      <main> 
          <Routes> 
              <Route 
                  path="/" 
                  view=move |cx| view! { cx, <SimpleComponent/> } />
              <Route 
                  path="demo1" 
                  view=move |cx| view! { cx, <Demo1 /> } />
              <Route 
                  path="demo2" 
                  view=move |cx| view! { cx, <Demo2 /> } />
          </Routes>
      </main>
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:46:07