A 51% attack is a breakdown of the security assumptions underlying proof-of-work, namely that it incentivizes actors strongly enough to behave cooperatively.
If an attack happens, it means those assumptions were wrong, and PoW should be discarded entirely. Switching to another hash function doesn't change anything. If the economic reality allows an actor to gain a hashrate majority with one function, there is no reason to assume it couldn't do the same with another hash function.
Of course, the community - at the social level - obviously has the possibility to jointly decide to make any changes to the consensus rules. Whether that is switching to another hash function, or a more narrow change such as deciding that a particular chain by a particular party is invalid. And the existence of that ability is something a would-be 51% attacker should take into account when weighing their odds. I feel this is mostly a mutually assured destruction like scenario; the impact of such a dramatic measure is likely very devastating even if it is successful.