Mercury is locked into a 3/2 spin-orbit resonance where it rotates three times on its axis for every two orbits around the sun. The stability of this equilibrium state is well established, but our understanding of how this state initially arose remains unsatisfactory. Unless one uses an unrealistic tidal model with constant torques (which cannot account for the observed damping of the libration of the planet) the computed probability of capture into 3/2 resonance is very low (about 7 per cent). This led to the proposal that core-mantle friction may have increased the capture probability, but such a process requires very specific values of the core viscosity. Here we show that the chaotic evolution of Mercury's orbit can drive its eccentricity beyond 0.325 during the planet's history, which very efficiently leads to its capture into the 3/2 resonance. In our numerical integrations of 1,000 orbits of Mercury over 4Gyr, capture into the 3/2 spin-orbit resonant state was the most probable final outcome of the planet's evolution, occurring 55.4 per cent of the time.