useControl + MapboxDraw: Cannot read properties of undefined (reading 'get') under React 19 + Next 16 + Turbopack
还没有人认领这个 Issue。
评估
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 新手友好度
- 48/100
- Issue 类型
- 缺陷
- 描述清晰度
- 基本清楚
- 活跃度
- 冷清
- 技术栈
- next.js, react, typescript
调研方向
从 useControl 的实现开始,重点关注其 useMemo/useEffect 生命周期,并将其与可复现示例中的手动 useEffect addControl 序列进行比较。检查第 87 行的 MapboxDraw api.js 调用,以及报告的 React 19 StrictMode/Turbopack 行为。当失败示例不再以 undefined ctx.store 到达 draw.add 时,即表示完成。
由索引模型根据 Issue 内容生成。
描述
Description
useControl<MapboxDraw>(...) fails on mount in a React 19 + Next.js 16 + Turbopack stack with the error:
TypeError: Cannot read properties of undefined (reading 'get')
at draw.add(feature)
The error originates in @mapbox/mapbox-gl-draw's api.add (line 87 of src/api.js), which calls ctx.store.get(feature.id). ctx.store is undefined (not null) at the moment of the call, meaning the draw instance's onAdd lifecycle hook never executed before draw.add was invoked.
A manual useEffect that calls map.getMap().addControl(draw) and then draw.add(feature) directly (bypassing useControl entirely) does not exhibit the bug under the same stack. This narrows the bug to useControl's lifecycle handling specifically, not to mapbox-gl-draw or the broader pattern of mounting mapbox-gl primitives from React effects.
Environment
react-map-gl@^7.1.9(issue likely also affects@vis.gl/[email protected]per related issues below)@mapbox/mapbox-gl-draw@^1.5.1mapbox-gl@^3.22.0[email protected][email protected](App Router, Turbopack dev mode, default StrictMode)- Windows 11 / Chrome (also reproduced on macOS per issue #2584's reporter)
Diagnostic strategies attempted (all failed)
We hit the error during a feature-flagged editor migration to mapbox-gl-draw. Five fix iterations across four mitigation strategies, all with the error appearing at the same call site (draw.add(feature) in the parent's hydration useEffect):
- Sync
setDrawReady(true)fromprops.onCreateinsideuseControl's factory. Errored:Cannot update a component while rendering a different component(factory runs inuseMemoduring render, and the parent'ssetStatefrom inside the child's render-phase factory is illegal). queueMicrotask(() => setDrawReady(true)). First error cleared. New error surfaced:Cannot read properties of undefined (reading 'get')fromdraw.add. Also fixed a second error (You must provide a featureId to enter direct_select mode) by switching the constructor'sdefaultModefrom a custom direct_select-extending mode tosimple_select.- Added a
drawSourcesReadygate driven by a one-shot'idle'event listener registered insideonLoad, in addition tomapLoadedanddrawReady. Hypothesis: the map'sidleevent fires only after both react-map-gl'sonLoadand mapbox-gl-draw's internal load-handler complete, so by then_ctx.storeshould be initialised. Outcome: error persisted at the same site. - Ported to the documented
useControl(onCreate, onAdd, onRemove)third-overload recipe. Factory returns theMapboxDrawinstance only; event wiring and parent-notification (props.onCreate(draw)) moved intoonAddso the parent receives the draw instance only afteruseControl'suseEffecthas invokedmap.addControl(draw)and triggeredMapboxDraw.onAdd(map)to set_ctx.store. Outcome: error persisted at the same site, despite the lifecycle ordering being structurally correct on paper.
After the fifth iteration we abandoned the migration and ran an empirical PoC: a manual useEffect-based mount that bypasses useControl. The PoC succeeds 10/10 across hard-refresh and client-side-navigation stress cycles under the same stack.
Workaround (manual addControl in useEffect)
This pattern works in the same stack where useControl<MapboxDraw> fails. Posted as data, not as a recommendation for the upstream API:
"use client";
import { useEffect, useRef, useState } from "react";
import Map, { type MapRef } from "react-map-gl";
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import "mapbox-gl/dist/mapbox-gl.css";
import "@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css";
const FEATURE: GeoJSON.Feature = {
type: "Feature",
properties: {},
geometry: {
type: "LineString",
coordinates: [[5.32, 60.39], [5.4, 60.0], [5.6, 59.5], [5.73, 58.97]],
},
};
export default function ManualPoc() {
const mapRef = useRef<MapRef>(null);
const [mapLoaded, setMapLoaded] = useState(false);
const [status, setStatus] = useState<string>("idle");
useEffect(() => {
if (!mapLoaded) return;
const map = mapRef.current?.getMap();
if (!map) return;
let draw: MapboxDraw | null = null;
try {
draw = new MapboxDraw({ displayControlsDefault: false });
map.addControl(draw); // synchronous; draw.onAdd runs here
const ids = draw.add(FEATURE); // succeeds
setStatus(`success: id=${ids[0]}`);
} catch (e) {
setStatus(`error: ${(e as Error).message}`);
}
return () => {
if (draw && map.hasControl(draw)) {
try { map.removeControl(draw); } catch {}
}
};
}, [mapLoaded]);
return (
<>
<div style={{ padding: 12, fontFamily: "monospace" }}>{status}</div>
<Map
ref={mapRef}
mapboxAccessToken={process.env.NEXT_PUBLIC_MAPBOX_TOKEN}
initialViewState={{ longitude: 5.5, latitude: 59.7, zoom: 6 }}
style={{ width: "100%", height: "calc(100vh - 40px)" }}
mapStyle="mapbox://styles/mapbox/light-v11"
onLoad={() => setMapLoaded(true)}
/>
</>
);
}
Reproducible failing example
The same component but using useControl<MapboxDraw>(onCreate, onAdd, onRemove) (the third-overload recipe) fails. Minimal failing pattern:
function DrawControl({ onCreate }: { onCreate: (d: MapboxDraw) => void }) {
const drawInstanceRef = useRef<MapboxDraw | null>(null);
useControl<MapboxDraw>(
() => {
const draw = new MapboxDraw({ displayControlsDefault: false });
drawInstanceRef.current = draw;
return draw;
},
({ map }) => {
const draw = drawInstanceRef.current;
if (draw) onCreate(draw);
},
() => {},
);
return null;
}
function ParentMap() {
const drawRef = useRef<MapboxDraw | null>(null);
const [drawReady, setDrawReady] = useState(false);
const [mapLoaded, setMapLoaded] = useState(false);
useEffect(() => {
if (!drawReady || !mapLoaded) return;
drawRef.current?.add({
type: "Feature", properties: {},
geometry: { type: "LineString", coordinates: [[0,0],[1,1]] },
}); // throws: Cannot read properties of undefined (reading 'get')
}, [drawReady, mapLoaded]);
return (
<Map onLoad={() => setMapLoaded(true)}>
<DrawControl onCreate={(d) => { drawRef.current = d; setDrawReady(true); }} />
</Map>
);
}
Hypothesised root cause
The empirical asymmetry (useEffect-driven addControl works; useControl-driven addControl does not) under the same React/Next/Turbopack stack suggests the bug lives in useControl's useMemo + useEffect choreography rather than in mapbox-gl-draw or in the broader pattern.
Two non-exclusive hypotheses:
-
useMemofactory orphans under React 19 StrictMode. React 19 invokesuseMemo's calculator twice in StrictMode dev (the second result is returned). If the first factory call constructs aMapboxDrawthat the parent ever holds a reference to (via a side effect in the factory body, or via some other capture path), and that reference'sonAddis never called byuseControl'suseEffect(which uses the second result), thendraw.add(...)on the first instance throws because_ctx.storeisundefined. -
Effect-ordering interleaving with Turbopack hot-mount cycles. Issues #2584 and #2588 document the same family of failures across
Marker(addTo),Source/Layer(addSource/addLayer), where the new mount's effects fire before the previous mount's cleanup runs.useControl's lifecycle may have a similar interleave window.
Manual useEffect mount avoids both: the draw instance is created in setup, used in setup, and torn down in cleanup, all in a single closure. There is no orphaned reference held by the parent and no separate factory-vs-effect timing.
Related open issues
- #2413 —
useControl + MapboxDrawbroke on Next 14.1 → 14.2 upgrade. Open since 2024-07-08, no maintainer response. - #2584 —
MarkercrashesCannot read properties of undefined (reading 'appendChild')on rapid client-side navigation in React 19 + Next 16. Open since 2026-04-03; confirmed by a second reporter. - #2588 —
Markercrashes oncacheComponentsActivity reappear in React 19 + Next 16. - #2410 — React 19 +
Source/LayerFragment-prop warnings.
The four issues plus this one suggest a class of failures, not isolated bugs. The common factor across all five: react-map-gl's effect-mounted child primitives misbehave under React 19's StrictMode + Next.js 16's Turbopack and Activity machinery.
Background
Filing as community contribution from a Front Carbon (CCS planning B2B SaaS) Editor 2.0 migration that abandoned useControl<MapboxDraw> after five iterations and pivoted to manual useEffect-based mount. The minimal reproducible code above is from our internal sandbox PoC (10/10 green for the manual pattern; 0/5 green for the useControl pattern under the same stack). Happy to provide a full minimal-reproduction repository if it helps narrow down the root cause.
Not blocking on a fix from our side; the workaround is acceptable for our use case. Posting in case it helps the maintainers correlate this with the four related open issues into a single root-cause investigation.
- 主要语言
- TypeScript
- 星标
- 8.5k
- 派生
- 1.3k
- PR 合并指标
- 30 天内没有已合并 PR
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 没有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
visgl/react-map-gl 的其他 Issue
-
DEFAULT_SETTINGS.maxBounds in @vis.gl/react-maplibre has 360° longitude span, triggers maplibre-gl-js#6148 crash via _updateSettings fallback可能重新可做 关联的 PR 已关闭且未合并。 未关闭
难度 2/5 1-3 小时 新手友好度 74/100
visgl/react-map-gl#2591 · 2 条评论 ·
-
[Bug] Mapbox geocoder example crashes: "i is not a function"可能已有人在做 @yuiseki 于 20 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 35/100
visgl/react-map-gl#2628 ·
-
[Bug] Scroll zoom stops short of maxZoom in controlled mode with MapLibre可能已有人在做 @sviat-barbutsa 于 33 天前认领。 未关闭bug
难度 3/5 半天 新手友好度 74/100
visgl/react-map-gl#2626 ·
-
[Bug] reuseMaps: Mapbox.reuse() infinite-loops (tab freeze) when the recycled map's container is the mount container可能已有人在做 @mikeyfarina 于 82 天前认领。 未关闭
难度 3/5 1-2 天 新手友好度 68/100
visgl/react-map-gl#2613 ·
-
feature
难度 5/5 一周以上 新手友好度 42/100
visgl/react-map-gl#2603 · 1 个 reaction ·
查看 visgl/react-map-gl 的全部 Issue
相似的 Issue
-
accessibility area:ci ci-test level:low priority:high type:test
难度 2/5 1-3 小时 新手友好度 71/100
skytuhua-org/Gen-V1#3132 · 1 条评论 ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 76/100
drmrd/vernacular#1238 ·
维护者通常 1 天内回复
-
question
难度 2/5 1-3 小时 新手友好度 65/100
-
enhancement migration-prioritized
难度 2/5 1-3 小时 新手友好度 88/100
Hudson-Pufferfish/local-party-console#136 ·
维护者通常 1 天内回复
-
priority:medium
难度 2/5 1-3 小时 新手友好度 75/100
维护者通常 1 天内回复