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

Phoenix LiveView中on_mount赋值current_user后模态框保存时丢失问题

问题分析与解决方案

核心原因

你遇到的current_user找不到的KeyError,本质是LiveComponent没有从父LiveView接收到current_user这个assign。虽然根LiveView通过on_mount注入了current_user,但LiveComponent不会自动继承父组件的所有assigns,必须显式传递。

具体修复步骤

  1. 传递current_user到FormComponent
    在渲染编辑用的FormComponent时(比如在WeightLive.Show或父组件的模板里),添加current_user: @current_user参数:

    <%= live_component @socket, HealthTrackerWeb.WeightLive.FormComponent,
      id: @weight.id,
      action: @live_action,
      weight: @weight,
      current_user: @current_user %>
    
  2. 确保组件接收并使用该assign
    在FormComponent的update/2或mount/3函数中,确认current_user被存入组件的assigns:

    def update(assigns, socket) do
      {:ok, assign(socket, assigns)}
    end
    

    然后在handle_event("save", _, socket)里,通过socket.assigns.current_user访问即可,不会再触发KeyError。

  3. 额外检查:确认on_mount覆盖所有需要的LiveView
    如果编辑功能对应独立的LiveView(而非组件),要确保该LiveView的路由或模块定义中,同样添加了on_mount HealthTrackerWeb.UserLiveAuth,保证current_user被注入。

验证要点

  • 触发save事件前,在组件模板中添加<%= inspect @current_user %>,确认该值存在;
  • 检查日志中组件的assigns输出,确认current_user已被传递。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 14:22:12