It’s an unfortunate and long-standing bug. See: Confused by behaviour of nested functions for more discussion.
Fortunately, it’s easy to avoid by defining an anonymous function instead:
function fx(n)
if n == 1
f = x -> 2x
else
f = x -> 3x
end
f
end