Skip to content

Commit 2f91872

Browse files
committed
fix(ssr): only cache computed getters during render phase
fix #5300
1 parent 25bc654 commit 2f91872

File tree

6 files changed

+75
-9
lines changed

6 files changed

+75
-9
lines changed

packages/reactivity/src/computed.ts

+7-4
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,18 @@ export interface WritableComputedOptions<T> {
2323
set: ComputedSetter<T>
2424
}
2525

26-
class ComputedRefImpl<T> {
26+
export class ComputedRefImpl<T> {
2727
public dep?: Dep = undefined
2828

2929
private _value!: T
30-
private _dirty = true
3130
public readonly effect: ReactiveEffect<T>
3231

3332
public readonly __v_isRef = true
3433
public readonly [ReactiveFlags.IS_READONLY]: boolean
3534

35+
public _dirty = true
36+
public _cacheable: boolean
37+
3638
constructor(
3739
getter: ComputedGetter<T>,
3840
private readonly _setter: ComputedSetter<T>,
@@ -45,15 +47,16 @@ class ComputedRefImpl<T> {
4547
triggerRefValue(this)
4648
}
4749
})
48-
this.effect.active = !isSSR
50+
this.effect.computed = this
51+
this.effect.active = this._cacheable = !isSSR
4952
this[ReactiveFlags.IS_READONLY] = isReadonly
5053
}
5154

5255
get value() {
5356
// the computed ref may get wrapped by other proxies e.g. readonly() #3376
5457
const self = toRaw(this)
5558
trackRefValue(self)
56-
if (self._dirty) {
59+
if (self._dirty || !self._cacheable) {
5760
self._dirty = false
5861
self._value = self.effect.run()!
5962
}

packages/reactivity/src/deferredComputed.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,14 @@ class DeferredComputedRefImpl<T> {
5858
// value invalidation in case of sync access; normal effects are
5959
// deferred to be triggered in scheduler.
6060
for (const e of this.dep) {
61-
if (e.computed) {
61+
if (e.computed instanceof DeferredComputedRefImpl) {
6262
e.scheduler!(true /* computedTrigger */)
6363
}
6464
}
6565
}
6666
this._dirty = true
6767
})
68-
this.effect.computed = true
68+
this.effect.computed = this as any
6969
}
7070

7171
private _get() {

packages/reactivity/src/effect.ts

+10-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
newTracked,
1010
wasTracked
1111
} from './dep'
12+
import { ComputedRefImpl } from './computed'
1213

1314
// The main WeakMap that stores {target -> key -> dep} connections.
1415
// Conceptually, it's easier to think of a dependency as a Dep class
@@ -54,9 +55,16 @@ export class ReactiveEffect<T = any> {
5455
active = true
5556
deps: Dep[] = []
5657

57-
// can be attached after creation
58-
computed?: boolean
58+
/**
59+
* Can be attached after creation
60+
* @internal
61+
*/
62+
computed?: ComputedRefImpl<T>
63+
/**
64+
* @internal
65+
*/
5966
allowRecurse?: boolean
67+
6068
onStop?: () => void
6169
// dev only
6270
onTrack?: (event: DebuggerEvent) => void

packages/runtime-core/src/componentOptions.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ import {
1919
LooseRequired,
2020
UnionToIntersection
2121
} from '@vue/shared'
22-
import { computed, isRef, Ref } from '@vue/reactivity'
22+
import { isRef, Ref } from '@vue/reactivity'
23+
import { computed } from './apiComputed'
2324
import {
2425
watch,
2526
WatchOptions,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { createSSRApp, defineComponent, h, computed, reactive } from 'vue'
2+
import { renderToString } from '../src/renderToString'
3+
4+
// #5208 reported memory leak of keeping computed alive during SSR
5+
// so we made computed properties created during SSR non-reactive in
6+
// https://github.com/vuejs/core/commit/f4f0966b33863ac0fca6a20cf9e8ddfbb311ae87
7+
// However, the default caching leads to #5300 which is tested below.
8+
// In Vue 2, computed properties are simple getters during SSR - this can be
9+
// inefficient if an expensive computed is accessed multiple times during render,
10+
// but because of potential mutations, we cannot cache it until we enter the
11+
// render phase (where no mutations can happen anymore)
12+
test('computed reactivity during SSR', async () => {
13+
const store = {
14+
// initial state could be hydrated
15+
state: reactive({ items: null }) as any,
16+
17+
// pretend to fetch some data from an api
18+
async fetchData() {
19+
this.state.items = ['hello', 'world']
20+
}
21+
}
22+
23+
const getterSpy = jest.fn()
24+
25+
const App = defineComponent(async () => {
26+
const msg = computed(() => {
27+
getterSpy()
28+
return store.state.items?.join(' ')
29+
})
30+
31+
// If msg value is falsy then we are either in ssr context or on the client
32+
// and the initial state was not modified/hydrated.
33+
// In both cases we need to fetch data.
34+
if (!msg.value) await store.fetchData()
35+
36+
expect(msg.value).toBe('hello world')
37+
return () => h('div', null, msg.value + msg.value + msg.value)
38+
})
39+
40+
const app = createSSRApp(App)
41+
42+
const html = await renderToString(app)
43+
expect(html).toMatch('hello world')
44+
45+
// should only be called twice since access should be cached
46+
// during the render phase
47+
expect(getterSpy).toHaveBeenCalledTimes(2)
48+
})

packages/server-renderer/src/render.ts

+6
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,12 @@ function renderComponentSubTree(
128128
comp.ssrRender = ssrCompile(comp.template, instance)
129129
}
130130

131+
// perf: enable caching of computed getters during render
132+
// since there cannot be state mutations during render.
133+
for (const e of instance.scope.effects) {
134+
if (e.computed) e.computed._cacheable = true
135+
}
136+
131137
const ssrRender = instance.ssrRender || comp.ssrRender
132138
if (ssrRender) {
133139
// optimized

0 commit comments

Comments
 (0)